Java:使用GridLayout输入矩阵
我正在尝试编写一个可以使用GridLayout输入任意大小的矩阵的函数,但是因为我找不到一个合适的方法来提取JTextField值来填充’mat’var(参见下面的FIXME) 。
/** * @mat: matrix declared in main (eg: mat[][] = new int[3][3];) * @rows: number of matrix rows (eg: int rows = 3;) * @columns: number of matrix columns (eg: 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; }
在此先感谢您的帮助!
- 使用JTable而不是
GridLayout
包含的一堆JTextField
要么
-
添加
putClientProperty
并从GridLayout
添加标识符Row
aColumn
-
将
JTextField
放到HashMap
-
我更喜欢
putClientProperty
(你可以多重播放数字或额外的信息..,单独的putClientProperty
数量不会以某种方式减少) -
取决于(不清楚)desing,你可以将
ActionListener
添加到JTextField
(加速器是ENTER key
)或DocumentListener
虚拟示例, JButton
和ActionListener
代码示例, putClientProperty
可从所有方法或添加到JTextField
Listeners
访问
在循环
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")); }
假设您有一个3行x 3列网格。 由于GridLayout按行添加,因此第二行的第1项将是您添加到网格中的第4项。 您可以通过调用panel.getComponent(3)来检索此项(零索引,因此第4项位于索引3)。
所以 – 您可以使用getComponent,根据列数和矩阵中的i,j坐标进行一些数学计算以找出正确的索引。