2012-11-23 36 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