1

我试图创建一个循环来在页面上多次创建这个 JComboBox。知道为什么这不起作用吗?

        String[] numbers = {"1","2","3","4","5","6","7","8","9","10"};
        JComboBox numberbox = new JComboBox(numbers); 
     for(int j = 1; j <= 12; j++){
        numberbox[j].setLocation(103,j*30);
        numberbox[j].setSize(47,26);
        numberbox[j].setSelectedIndex(1);
        numberbox[j].setBackground(Color.WHITE);
        panelForTextFields.add(numberbox[j]);
        numberbox[j].addActionListener(this);
     }

我相信它是循环部分以外的工作代码。当我用这段代码替换它时,它会打印一个可以按我想要的方式工作的 JComboBox。

        String[] numbers = {"1","2","3","4","5","6","7","8","9","10"};
        JComboBox numberbox = new JComboBox(numbers); 
        numberbox.setLocation(103,30);
        numberbox.setSize(47,26);
        numberbox.setSelectedIndex(1);
        numberbox.setBackground(Color.WHITE);
        panelForTextFields.add(numberbox);
        numberbox.addActionListener(this);

我在 Eclipse 中收到的错误是“表达式的类型必须是数组类型,但它解析为 JComboBox”

4

2 回答 2

2

我在 Eclipse 中收到的错误是“表达式的类型必须是数组类型,但它解析为 JComboBox”

是的,该numberbox变量未声明为数组,但您尝试将其用作数组,因此 Java(不是 Eclipse)正确地告诉您不能这样做。首先将变量声明为一个数组(或者最好是一个ArrayList<JComboBox>),然后在 for 循环中创建每个JComboBox。此外,使用布局管理器并避免组件的绝对定位。

IE,

String[] numbers = {"1","2","3","4","5","6","7","8","9","10"};
JPanel myGridLayoutUsingJPanel = new JPanel(new GridLayout(0, 1));
JComboBox[] combos = new JComboBox[MAX_COMBOS]; // MAX_... is a constant
for (int i = 0; i < combos.length; i++) {
  combos[i] = new JComboBox(numbers);
  combos[i].addActionListener(someActionListener);
  myGridLayoutUsingJPanel.add(combos[i]);
}

// add myGridLayoutUsingJPanel to the GUI...
于 2013-05-24T01:11:53.293 回答
1

您正在循环中更新相同的 JCombobox。您还需要在 te 循环中执行 new 以创建和添加不同的 JCombbox。这是更新的代码:

 String[] numbers = {"1","2","3","4","5","6","7","8","9","10"};
 JComboBox numberbox = null;
 for(int j = 1; j <= 12; j++){
    numberbox = new JComboBox(numbers); 
    numberbox.setLocation(103,j*30);
    numberbox.setSize(47,26);
    numberbox.setSelectedIndex(1);
    numberbox.setBackground(Color.WHITE);
    panelForTextFields.add(numberbox);
    numberbox.addActionListener(this);
 }
于 2013-05-24T01:13:11.220 回答