Sign in to follow this  
Stuart_Mastrgamr

Getting specific value for JButton

Recommended Posts

I'm trying to get a specific value for a JButton in an array of JButtons, Here is part of my code:

[code]

//create and setup the board panel
JPanel board = new JPanel();
board.setLayout(new GridLayout(3, 3));

for(int i = 0; i < spot.length; i++){ //spot array has 9 elements
spot[i] = new JButton(); //initialize each spot to a new JButton
spot[i].setText("-");
spot[i].setFont(new Font(this.getFont().getFontName(), this.getFont().getStyle(), 30));//used to change the font size
spot[i].addActionListener(this); //give each spot an ActionListener
board.add(spot[i]); //add the buttons
}

this.add(board, BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
String buttonText = e.getActionCommand();

if(buttonText.equals("-")){
spot[e.getID()].setText("Changed");
}

}
[/code]


In the ActionListener method i'm trying to set the text on a specific button a user clicks on to the changed text. I can't find anything in the Java API to help me, is there some other way to do this?

Share this post


Link to post
Share on other sites
You can inspect and cast e.getSource() to a JButton in your event handler. Another option is to attach an anonymous inner ActionListener to each button, which means the source is implied.

Don't use e.getId(), it has no relationship with th index of the button in your array.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this