2015-12-19 44 views
0

我创建了一个Sudoku板,并且创建了9个JPanel,每个包含9个JTextFields。我的问题是,我不知道如何从一个SPECIFIC面板获取来自JTextField的输入。从JPanels数组中的JTextField中的数组访问数据? -Sudoku

这是我如何创建每个JTextField和JPanel。我已经用另一种方法初始化了它们。

private JPanel panel1, panel2, panel3, panel4, panel5, panel6, panel7, panel8, panel9; 

private JPanel[][] smallgrids = { {panel1, panel2, panel3}, {panel4, panel5, panel6}, {panel7, panel8, panel9} }; 

private JTextField cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9; 

private JTextField[][] cells = { {cell1, cell2, cell3}, {cell4, cell5, cell6}, {cell7, cell8, cell9}}; 

这是我做过什么让每个JTextField中输入:

String input; 
for(int x = 0; x < 3; x++){ 
    for(int y = 0; y < 3; y++){ 
     input = cells[x][y].getText();   
     cells[x][y].setText(input); 

      } 
     } 
     //this was my test to see if it would print the correct value 
     System.out.println(input[0][0]); 

我的问题是,循环访问来自细胞的输入,而不指定它是哪个面板。我如何指定我从哪个面板访问输入?对不起,如果措辞有点混乱。如果需要,我可以发布我的所有代码。

而这正是我的板是这样的: enter image description here

回答

0

建议:

  1. 创建JTextField中的9×9阵列 - 现在的主要问题已经解决任何和所有JTextField是通过简单使用适当的索引即可访问。
  2. 创建一个3 x 3的JPanel数组,并从上面为每个JPanel 9提供适当的JTextFields。
  3. 最重要的是,创建一个9 x 9的int类型的数组,或者更好的枚举类型,因为soduku数字并不像真正的数字,而是任何9个项目的独特项目集合都可以工作。
  4. 该车型将拥有9个方格对应于JPanels,并将于9枚举项目每个
  5. 您还需要行和列集合,以测试行和列的逻辑有效性(没有重复的枚举项)。
0

您的smallgrids是JPanel的二维数组。你的单元格是JTextFields的二维数组。从你的代码的外观你现在只有一个。

使用您当前的设计,您需要为您的smallgrids数组中的每个JPanel使用一个JTextFields网格。我可能会创建和初始化这些值是这样的:

// 1st 2 indices are outer grid, 2nd 2 are the inner grid. 
grid[x1][y1][x2][y2].getText(); 
:由

public void init_grids(){ 
    // create the outer grid. 
    JPanel[][] grid = NEW JPanel[3][3]; 

    // for each cell of the outer grid 
    for (int x1 = 0; x1 < 3; x1++) { 
     for (int y1 = 0; y1 < 3; y1++) { 

      // create the array of textfields for this panel. 
      JTextField[][] textFields = new JTextField[3][3]; 
      grid[x1][y1] = textFields; 

      // for each cell of the inner grid 
      for (int x2 = 0; x2 < 3; x2++) { 
       for (int y2 = 0; y2 < 3; y2++) { 

        // create the text field. 
        textFields[x2][y2] = new JTextField(); 
       } 
      } 
     } 
    } 
} 

访问它