Jump to content
  • Advertisement
Sign in to follow this  
Stuart_Mastrgamr

Getting specific value for JButton

This topic is 2533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to get a specific value for a JButton in an array of JButtons, Here is part of my 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 = new JButton(); //initialize each spot to a new JButton
spot.setText("-");
spot.setFont(new Font(this.getFont().getFontName(), this.getFont().getStyle(), 30));//used to change the font size
spot.addActionListener(this); //give each spot an ActionListener
board.add(spot); //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");
}

}



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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!