Java: input a matrix using GridLayout

前端 未结 2 1203
忘掉有多难
忘掉有多难 2020-12-07 04:57

I am trying to write a function that can input a matrix of any size using a GridLayout, but I\'m stuck since I can\'t find an appropriate way of extracting the JTextField va

相关标签:
2条回答
  • 2020-12-07 05:36

    Let's say you have a 3-row x 3-column grid. Since GridLayout adds by rows, then the 1st item of the second row would be the 4th item that you added to the grid. You could retrieve this item by calling panel.getComponent(3) (zero index so 4th item is at index 3).

    So - you could just use getComponent, doing a little math to figure out the right index based on the number of columns and the i,j coordinates in the matrix.

    0 讨论(0)
  • 2020-12-07 05:38
    • use JTable instead of bunch of JTextField layed by GridLayout

    or

    • add there putClientProperty and to add identifier Row a Column from GridLayout

    • put JTextField to the HashMap

    • I would be preferring putClientProperty (you can to multiplay number or additional infos.., number of separate putClientProperty isn't somehow reduced)

    • depends of (not clear) desing, you can to add ActionListener to JTextField (accelerator is ENTER key) or DocumentListener

    virtual example, code example for JButton and ActionListener, putClientProperty is accesible from all methods or Listeners added to JTextField

    in the loop

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

    and get from ActionListener (for example)

    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 讨论(0)
提交回复
热议问题