Java: enter matrix using GridLayout

I am trying to write a function that can input a matrix of any size using GridLayout, but I am stuck as I cannot find a suitable way to retrieve JTextField values ​​to populate var 'mat' (see FIXME below).

    /**
     * @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;
    }

Thanks in advance for your help!

+1
source share
2 answers
  • use jtable instead of bundle JTextFieldplacedGridLayout

or

  • add there putClientPropertyand add id Rowa ColumnfromGridLayout

  • enter JTextFieldinHashMap

  • I would prefer putClientProperty(you can multiply the number or additional information .., the number of individual ones is putClientPropertynot somehow reduced)

  • ( ) desing, ActionListener JTextField ( ENTER key) DocumentListener

, JButton ActionListener, 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"));
}
+3

, 3- . GridLayout , , . , panel.getComponent(3) ( , 4- 3).

, getComponent, , , i, j .

+1

All Articles