我需要一些帮助,我是刚接触java的,所以我可能需要改变很多东西。我的结果是:
[Goya, Scoop 2000 W, 123]如果我尝试添加更多,它将显示:
[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]我真正需要的是这样的东西:
[HMI, Scoop 2000 W, 123,]
[Fresnel, Set light 1000 W De Sisti, 124]
[Goya, Set light 1000 W De Sisti, 456]这是我的代码:
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());
}
}
}
}发布于 2015-09-05 21:21:49
你想要的是矩阵。可以使用String[][]类型的数组,也可以使用类型List<List<String>>的列表。
我还简化了您的代码(使用泛型,分解出逻辑),但是所有这些转换和intanceof可能都是您应该改进的糟糕设计的标志。
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;
}如果其中一个字符串空了,我不知道你想怎么处理它。
https://stackoverflow.com/questions/32417747
复制相似问题