Return the index of clicked button?

前端 未结 4 656
执笔经年
执笔经年 2020-12-02 02:47

I have got an array of 30 buttons []. I have a variable buttonClicked. When I press the button how can I get the index and store the index number in the buttonClicked?

相关标签:
4条回答
  • 2020-12-02 03:20

    You can find the button in ActionEvent.getSource(). To find the index it is just a matter of iterating through the array, looking for that particular button.

    0 讨论(0)
  • 2020-12-02 03:21

    I prefer the strategy suggested by aioobe, but here is another way.

    buttons[btnNumber - 1] = new JButton("label " + btnNumber);
    buttons[btnNumber - 1].setActionCommand("" + btnNumber);
    // ...
    
    // ...later.. in the actionPerformed() method
    String num = actionEvent.getActionCommand();
    int index = Integer.parseInt(num);
    // ..proceed..
    
    0 讨论(0)
  • 2020-12-02 03:23

    The prettiest way is using Component.setName. Then you don't even need to maintain variables with your components - you can go straight off of the name

    0 讨论(0)
  • 2020-12-02 03:44

    1) putClientProperty

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

    and getClientProperty

    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"));
    }
    

    2) ActionCommand

    0 讨论(0)
提交回复
热议问题