2012-11-23 32 views
1

我想寫一個函數,可以使用GridLayout輸入任何大小的矩陣,但我卡住了,因爲我找不到合適的方式來提取JTextField值來填充'mat'var(參見下面的FIXME)。Java:使用GridLayout輸入矩陣

/** 
    * @mat: matrix declared in main (e.g: mat[][] = new int[3][3];) 
    * @rows: number of matrix rows (e.g: int rows = 3;) 
    * @columns: number of matrix columns (e.g: int columns = 3;) 
    */ 
    public static int[][] inputMatrix(int[][] mat, int rows, int columns) 
    { 
     JPanel panel = new JPanel();  
     panel.setLayout(new GridLayout(rows,columns)); 

     for (int a=0; a<(rows*columns); a++) 
     { 
      panel.add(new JTextField(a)); 
     } 

     if (JOptionPane.showConfirmDialog(null, panel, "Enter the matrix", JOptionPane.OK_CANCEL_OPTION) 
             == JOptionPane.OK_OPTION) 
     { 
      for(int a=0; a<(rows*columns); a++){ 
       for(int b=0; b<rows; b++){ 
        for(int c=0; c<columns; c++){ 
         /* FIXME: find how to extract JTextField values. */ 
         mat[b][c] = JTextField.a.getText(); 
        } 
       } 
      } 
     } 

     return mat; 
    } 

在此先感謝您的幫助!

回答

3
  • 使用JTable,而不是由GridLayout

奠定一堆 JTextField
  • 添加有putClientProperty並添加identifier Row a Column from GridLayout

  • JTextFieldHashMap

  • 我會寧願putClientProperty(你可以到多重..,是不是在某種程度上減少了單獨putClientProperty數數或額外的相關信息)

  • 取決於(不清楚)德興,你可以添加ActionListenerJTextField(加速器是ENTER key)或DocumentListener

虛擬例如,對於JButtonActionListener代碼示例中,putClientProperty是從所有方法或入店Listeners加入JTextField

在循環

buttons[i][j].putClientProperty("column", i); 
buttons[i][j].putClientProperty("row", j); 
buttons[i][j].addActionListener(new MyActionListener()); 

,並從ActionListener的(例如)

public class MyActionListener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     JButton btn = (JButton) e.getSource(); 
     System.out.println("clicked column " + btn.getClientProperty("column") 
       + ", row " + btn.getClientProperty("row")); 
} 
+0

嗨,JTable的方式看起來不錯,你可以詳細一點嗎? 我會看看另一個。 ty – user1847810

+1

@ user1847810從[此鏈接]開始(http://docs.oracle.com/javase/tutorial/uiswing/components/table.html)。所有Swing組件在Oracle/Sun都有相應的教程,這幾乎都是一個非常好的起點。 –

+0

@GuillaumePolet會做,謝謝! – user1847810

1

比方說,你有3行×3列網格。由於GridLayout按行添加,因此第二行的第一項將成爲您添加到網格中的第四項。您可以通過調用panel.getComponent(3)(零索引,因此第4項在索引3)來檢索此項目。

所以 - 你可以使用getComponent,根據列的數量和矩陣中的i,j座標計算出正確的索引。

+0

嗨,我試過'mat [b] [c] = Integer.parseInt(panel.getComponent(a));'但它說「無法從組件轉換爲int」。 我在這裏錯過了什麼嗎? ty – user1847810

+0

@ user1847810組件本身不是'int'(但可能是'JTextField')。你可以試試這個:'mat [b] [c] = Integer.parseInt(((JTextField)panel.getComponent(a)).getText());'。但我的建議是遵循mKorbel解決方案,並使用實際上用於您的目的的JTable。 –

+0

@GuillaumePolet這對我很有用,但是看起來很髒。 – user1847810