导致JComboBox不被引用的循环

时间:2013-03-23 03:07:18

标签: java swing loops jcombobox sudoku

我正在研究解决数独谜题的Java代码。逻辑还没有实现,但我遇到了使用循环来创建我的JComboBox的问题。我的代码编译并运行没有错误,但它只将右下角的3x3窗格转换为JLabel。我相信这个问题是由下面的循环引起的。

for (int boxRow = 0; boxRow<3; boxRow++){
  for(int boxCol = 0; boxCol<3; boxCol++){
    boxes[boxRow][boxCol] = new JPanel();
    boxes[boxRow][boxCol].setLayout(new GridBagLayout());
    for (int row = 0; row < 3; row++){
      for(int col = 0; col < 3; col++){
        comboBox[row][col] = new JComboBox(sudokuChoose);
        constraints.weightx = 1;
        constraints.weighty = 1;
        constraints.gridx = col;
        constraints.gridy = row;
        boxes[boxRow][boxCol].add(comboBox[row][col], constraints);
      }
    }
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.gridx = boxRow;
    constraints.gridy = boxCol;
    add(boxes[boxRow][boxCol], constraints);
    boxes[boxRow][boxCol].setVisible(true);
  }
}


    for(int boxRow = 0; boxRow<3; boxRow++){
  for(int boxCol = 0; boxCol<3; boxCol++){
    labelBoxes[boxRow][boxCol] = new JPanel();
    labelBoxes[boxRow][boxCol].setLayout(new GridBagLayout());
    for(int row = 0; row < 3; row++){
      for(int col = 0; col < 3; col++){
        tempComboText = (String)comboBox[row][col].getSelectedItem();
        label[row][col] = new JLabel();
        //System.out.println(comboBox[row][col]);
        //System.out.println((String)comboBox[row][col].getSelectedItem());
        label[row][col].setText(tempComboText);
        constraints.weightx = 1;
        constraints.weighty = 1;
        constraints.gridx = col;
        constraints.gridy = row;
        add(label[row][col], constraints);
        label[row][col].setVisible(true);
      } 
    }
  }
}

第一个创建了9个JComboBox,它们位于JPanel中。共有9个JPanel,共创建了81个JComboBox。但是,在创建框时,每个JPanel中每个对应的JComboBox的名称是相同的。因此,前8个JPanel中没有与JComboBox相关联的名称。在第二个中,我使用第一个中使用的相同循环结构转换JComboBox,但由于前8个JPanel中的JComboBox没有名称,因此无法访问它们并且无法从它们读取信息。关于如何解决这个问题的任何想法?

0 个答案:

没有答案