2015-12-19 46 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(); 
       } 
      } 
     } 
    } 
} 

訪問它