2016-12-02 63 views
0

我製作了3x3魔方檢查器。我只是想知道如何能夠將我的9個JTextFields存儲在數組中?
這樣我就可以通過二維數組,並迅速分配值的JTextField的循環,因爲我在我的存儲值的方式是遠遠高效...
您可以在NetBeans中創建一個JTextFields數組嗎?

int[][] grid = new int[3][3]; 
    grid[0][0] = new Integer(one.getText()); 
    grid[0][1] = new Integer(two.getText()); 
    grid[0][2] = new Integer(three.getText()); 
    grid[1][0] = new Integer(four.getText()); 
    grid[1][1] = new Integer(five.getText()); 
    grid[1][2] = new Integer(six.getText()); 
    grid[2][0] = new Integer(seven.getText()); 
    grid[2][1] = new Integer(eight.getText()); 
    grid[2][2] = new Integer(nine.getText()); 
+2

like'JTextFields [] [] = new JTextFields [3] [3];'? –

回答

0

你想存儲JTextField的在一個數組或數組中的Integer值?這會將Integer存儲爲示例代碼中的代碼,但您可以輕鬆地將第7行上的分配更改爲新的JTextField。

private static final int ROWS_NUM = 3; 
private static final int COLS_NUM = 3; 
int[][] grid = new grid[ROWS_NUM][COLS_NUM]; 
int counter = 0; 
for(int i=0; i<ROWS_NUM; i++) { 
    for(int j=0; j<COLS_NUM; j++) { 
     grid[i][j] = new Integer(++counter); 
    } 
} 
+0

我想要將JTextFields存儲在一個數組中,並通過循環運行網格後,我希望它將用戶輸入的值存儲在JTextFields中 – JAVANOOB

1

在最簡單的方式,如果你想這樣做在一個循環,你應該在一個列表,數組或Java語言支持的任何列表對象創建的JTextField對象。因爲你想按照一定的順序獲得值並在循環中完成。

JTextField[] fields = new JTextField[9]; 
//set the index of text field 
int fieldIndex = 0; 
int[][] grid = new int[3][3]; 
for(int i = 0; i<3; i++){ 
    for(int j = 0; j<3; j++){ 
     //JTextField value will be string, if you want to get integer from string you should do this. Otherwise you can generate string matrix to keep values as a string. 
     grid[i][j] = Integer.getInteger(fields[fieldIndex].getText()); 
     fieldIndex++; 
    } 
} 
相關問題