Home > Mobile >  How to refer to the object on which an action was performed
How to refer to the object on which an action was performed

Time:10-21

I created an ArrayList of JButtons using a for loop, so I don't have a specific name for each object. In the actionPerformed() method, I want to get "the indexOf(the button that was just pressed). Using the 'this' keyword, it refers to the overall class this is defined in, not the object that was pressed.

public class Game implements ActionListener
{   
    public void actionPerformed(ActionEvent event)
    {
        int temp = this.buttons.indexOf(this);
    }
}

CodePudding user response:

The actionPerformed() method has the ActionEvent as parameter. Use the getSource() method to find out which object fired the event.

CodePudding user response:

Here is first solution. You have to do some work on your side so the Button has name which you can give when create the buttons and then get it in the ActionEvent event. In this case you can use the internal ActionEvent getSource() JComponent getName() methods

private static List<JButton> buttons = new ArrayList<>();
static class MyListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        Integer i = Integer.valueOf(((JComponent) e.getSource()).getName());
        JButton pressedButton = buttons.get(i);
        //... Work here with pressedButton or i - index 
    }
}

public static void main(String[] args) {
    for(int i = 0; i< 10; i  )
    {
        JButton btn = new JButton();
        MyListener myListener = new MyListener();
        btn.addActionListener(myListener);
        btn.setName(Integer.valueOf(i).toString()); // here set the index in the button name
        // Button name is different from btn.setText("My Button");
        // setText actually will displayed on the button itself the label 
        buttons.add(btn);
    }
}

==================================================

This is second solution. This time you set the index on the creation of the Button Listener (inside the constructor). Here you use class parameter which will memorize which was the button index. Then when you are using it and it will know already which is the button.

private static List<JButton> buttons = new ArrayList<>();
static class MyButtonListener implements ActionListener {
    int buttonIndex;
    public MyButtonListener(int i) {
        buttonIndex = i;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton pressedButton = buttons.get(buttonIndex);
        //... Work here with pressedButton or buttonIndex  
    }
}

public static void main(String[] args) {
    for(int i = 0; i< 10; i  )
    {
        JButton btn = new JButton();
        MyButtonListener myListener = new MyButtonListener(i); //Here set the index in the constructor
        btn.addActionListener(myListener);
        buttons.add(btn);
    }

}

Best of luck to all!

  • Related