get position of the button on gridlayout

前端 未结 2 2073
不知归路
不知归路 2021-01-26 11:47

How to get position(I mean row and column) of the clicked button with gridlayout?

public void init(final Container pane) {
    JPanel controls = new JPanel();
          


        
2条回答
  •  不要未来只要你来
    2021-01-26 12:20

    In this case, you don't even have to search for the indices, because you know them when the button is created:

    for (int i = 0; i < puzzle.getSize(); i++) {
        int k = puzzle.getListItem(i);
        if (k == puzzle.getEmptyFlag())
            controls.add(new JLabel(""));
        else {
            JButton jb = new JButton(String.valueOf(k));
    
            final int rowIndex = i / size;
            final int columnIndex = i % size;
    
            // Using an ActionListener, as Hovercraft Full Of Eels already told you:
            jb.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("rowIndex "+rowIndex+" columnIndex "+columnIndex);
                }
    
            });
            controls.add(jb);
        }
    }
    

提交回复
热议问题