如何创建一个JComboBox循环,以便多次出现相同的组合框?

时间:2013-05-24 01:09:32

标签: java swing user-interface jcombobox

我试图创建一个循环来在页面上多次创建这个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”

2 个答案:

答案 0 :(得分:2)

  

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

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

即,

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...

答案 1 :(得分:1)

您正在循环中更新相同的JCombobox。您还需要在te循环中执行新操作以创建和添加不同的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);
 }