Java:使用GridLayout输入矩阵
作者:互联网
我正在尝试编写一个可以使用GridLayout输入任意大小的矩阵的函数,但是因为我找不到合适的方法来提取JTextField值以填充’mat’var(参见下面的FIXME) .
/**
* @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;
}
在此先感谢您的帮助!
解决方法:
>使用JTable而不是GridLayout铺设的JTextField束
要么
>添加putClientProperty并添加identifier Row
a Column
from GridLayout
>将JTextField放入HashMap
>我会更喜欢putClientProperty(你可以多重播放数字或额外的信息..,单独的putClientProperty数量不会以某种方式减少)
>取决于(不清楚)desing,你可以将ActionListener添加到JTextField(加速器是ENTER键)或DocumentListener
虚拟示例,JButton和ActionListener的代码示例,putClientProperty可从所有方法或添加到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"));
}
标签:grid-layout,java,matrix,input,swing 来源: https://codeday.me/bug/20190928/1825882.html