0

I need some help, I'm new to java, so probably I will have to change a lot of things. I'm having this result:

[Goya, Scoop 2000 W, 123]

And if I try to add more, it will display:

[HMI, Scoop 2000 W, 123]
[HMI, Scoop 2000 W, 123, Fresnel, Set light 1000 W De Sisti, 124]
[HMI, Scoop 2000 W, 123, Fresnel, Set light 1000 W De Sisti, 124, Goya, Set light 1000 W De Sisti, 456]

And what I actually need is something like that:

[HMI, Scoop 2000 W, 123,]
[Fresnel, Set light 1000 W De Sisti, 124]
[Goya, Set light 1000 W De Sisti, 456]

Here is my code:

Component[] componente = painelMain.getComponents();
    list = new ArrayList();
    for (int i = 0; i < componente.length; i++) {
        if (componente[i] instanceof JTextField) {
            JTextField textfield = (JTextField) componente[i];
            if (!"".equals(textfield.getText())) {
                list.add(textfield.getText());
                System.out.println(list);
            }
        } else if (componente[i] instanceof JComboBox) {
            JComboBox combo = (JComboBox) componente[i];
            if (!"".equals(combo.getSelectedItem())) {
                list.add(combo.getSelectedItem());
            }
        }
    }
}
2
  • 1
    He wants a matrix instead of a flat list Commented Sep 5, 2015 at 21:21
  • It sounds like you should be creating a new type to represent that combination of three values... (We can't really tell what they mean at the moment...) Commented Sep 5, 2015 at 21:23

1 Answer 1

2

What you want is a matrix. You can either use an array of type String[][] or a list of type List<List<String>>.

I also simplified your code (use of generics, factored out logic), however all these casts and intanceof are probably the sign of a bad design you should improve.

Component[] components = painelMain.getComponents();
List<List<String> list = new ArrayList<>();
List<String> line;

int i = 0, numCols = 3;
for (Component component : components) {
    if (i % numCols == 0) {
        line = new ArrayList<>();
        list.add(line);
    }
    String content = "";
    if (component instanceof JTextField) {
        content = ((JTextField) component).getText();            
    } else if (component instanceof JComboBox) {
        content = ((JComboBox<String>) component).getSelectedItem();
    }

    if (!content.isEmpty()) {
        line.add(content);
    }
    i = (i + 1) % 3;
}

There's an edge case if one of the strings gets empty, I don't know how you want to handle it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.