Java: input a matrix using GridLayout

大兔子大兔子 提交于 2019-11-28 02:22:26
mKorbel
  • 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"));
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!