programmer
programmer

Reputation: 4901

Return index of a clicked JButton in Java swing

I have the following Java code: I have a for loop and I'm creating JButtons. I would like to return the index of the clicked button. So i use:

    JButton jbtn = (JButton) e.getSource();

Is there any method that returns the JButton's index?

My code is as follows:

for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {

    ListofJButtons.get(button).addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("I clicked on button !");
            JButton buttonSource = (JButton) e.getSource();
            System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
        }
    } );

}//for loop

Is it possible to get the Index of the clicked JButton?

thanks

Upvotes: 0

Views: 2018

Answers (3)

Tim B
Tim B

Reputation: 41168

There are several ways. The simplest would be to do:

for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {
    final int index = button;
    ListofJButtons.get(button).addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // Because index is final I can access it here and know the index
            System.out.println("I clicked on button "+index+"!");
            JButton buttonSource = (JButton) e.getSource();
            System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
        }
    } );
}//for loop

The other simplest way would be just to do ListofJButtons.indexOf(buttonSource).

Upvotes: 1

AbhinavRanjan
AbhinavRanjan

Reputation: 1646

From ActionEvent you can do getActionCommand or from button you can get the getText or getLabel. Since buttons do not have any property which gives them a index you can't get the index. Index in not defined for them.

Upvotes: 1

Ren&#233; Link
Ren&#233; Link

Reputation: 51343

I guess ListofJButtons is a java.util.List. If so you can use

JButton buttonSource = (JButton) e.getSource();
int index = ListofJButtons.indexOf(buttonSource);

Upvotes: 1

Related Questions