Changing the color of a JButton with click won't work

public class LevelEditorButton extends JButton
{
/**
 * 
 */
private static final long serialVersionUID = 1L;
private int i;

public int getState()   {return i;}
public void increaseState()
{
    if(i == 2)
        i = 0;
    else
        i++;
    changeState();
}

public LevelEditorButton()
{
    i = 0;
    changeState();
    this.setOpaque(true);
}
public void changeState()
{
    if(i == 0)
        this.setBackground(Color.GREEN);
    else if(i == 1)
        this.setBackground(Color.RED);
    else 
        this.setBackground(Color.BLACK);
    this.setOpaque(true);
}
}

public class ChangeColorButtonListener extends LevelEditorButton implements ActionListener
{
     @Override
     public void actionPerformed(ActionEvent ae) 
    {
    this.increaseState();
    }

}

Programming on my mac always tends to give me weird bugs with JButtons, so I'm kinda lost in where to go from here. When I debug it, it shows that the color of the button has changed but won't show up on the screen. I've tried repaint(), revalidate() and updateUI(). Any help would be greatly appreciated.

Answers


The problem is that you never apply your ActionListener to the button. Two solutions for that:

make a constructor and apply here itself as listener

ChangeColorButtonListener(){
        this.addActionListener(this);
    }

or do it in the calling class like this:

ChangeColorButtonListener  ccb = new ChangeColorButtonListener();
ccb.addActionListener(ccb);

Need Your Help

Find illegal character \0 in Netbeans

java regex netbeans

I have a file opened in netbeans with last line filled with character \0. This character remains invisible and cause netbeans to give 'illegal character' error.

how to access google calendar API methods

java google-calendar google-api-java-client

I am new to Google APIs and am trying to create an app based on the Google Calendar API sample described here:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.