Sign in to follow this  
CyberSlag5k

[java] problem with java actionlistener

Recommended Posts

I have an array of JButtons in my Java project. I would like the text they display to change as they are pressed. They all have the same starting text (a null string) so I am having difficulty discerning which button was pressed. Here's some code:
public class myGame implements ActionListener
{
public static class main()
{
JFrame win = new JFrame();
JButton[] buttons = new JButton[9];
Container pane = win.getContentPane();
JPanel board = new JPanel(new GridLayout(3, 3));

for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].setFont(new Font("Times new roman", Font.BOLD, 60));
buttons[i].setForeground(Color.BLUE);
buttons[i].addActionListener(this);
board.add(buttons[i]);
}
pane.add(board, BorderLayout.CENTER);

public void actionPerformed(ActionEvent event)
{
String buttonText = event.getActionCommand();
if(buttonText.equals(""))
{
event.getSource().setText("Set!");            
}
}
}


I thought that line "event.getSource().setText("Set!");" would return the source of the action (the button that was pressed) and so I could just use the setText function to change its text, but if I do that I get an error message saying "cannot resolve symbole - method setText(java.lang.String)". So apparently getSource doesn't do what I thought it did. Any suggestions?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Try casting the object returned from getSource() to a JButton like this:
((JButton)event.getSource()).setText("Set!");

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by CyberSlag5k
They all have the same starting text (a null string) so I am having difficulty discerning which button was pressed.


Apart from the object-ref, you should be able to manually use:

.setActionCommand( String )

to attach a different unique ID to each button, even without displaying that command on the button (IIRC). It doesn't look like you need this any more, but it may be useful to you to know; it is *especially* helpful when dealing with buttons with image but no text :) where you still need to filter on the action command...

Share this post


Link to post
Share on other sites
Also, don't JButtons allow adding ActionListeners? So then you could extend JButton to implement ActionListener, and in your subclass' constructor, add the button to itself as a listener. Then each button *knows* it got the action from itself, and can set its own properties, like objects are supposed to :)

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