Reputation: 335
I have this program that when I click a button the color should change everytime I click on it. The first time I click it will work just fine. However when I click again it is not working anymore. Am I missing something in my code?Heres my code:
public class TrafficLight extends Frame implements ActionListener{
protected Color red;
protected Color yellow;
protected Color orange;
Button button;
Panel panel;
public TrafficLight(){
red = Color.RED;
yellow = Color.BLACK;
orange = Color.BLACK;
button = new Button("Change Color");
add(button,BorderLayout.SOUTH);
button.addActionListener(this);
}
@Override
public void paint(Graphics graphics){
graphics.drawRect(200, 50, 100, 300);
graphics.setColor(red);
graphics.fillOval(200, 50, 100, 100);
graphics.setColor(yellow);
graphics.fillOval(200,150,100, 100);
graphics.setColor(orange);
graphics.fillOval(200,250,100, 100);
}
public static void main(String[] args) {
TrafficLight light = new TrafficLight();
light.setSize(500,500);
light.setTitle("Traffic Light");
light.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
System.out.print(yellow);
if(event.getSource() == button){
if(red == red){
red = Color.BLACK;
yellow = Color.YELLOW;
}
else if(yellow == yellow){
yellow = Color.BLACK;
orange = Color.ORANGE;
}
System.out.print(yellow);
repaint();
}
}
}
Upvotes: 1
Views: 41
Reputation: 347194
Your problem is, you're testing equality of an object with itself, which will always be true...
if (red == red) {
I think you want something more like...
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
if (red == Color.RED) {
red = Color.BLACK;
yellow = Color.YELLOW;
} else if (yellow == Color.YELLOW) {
yellow = Color.BLACK;
orange = Color.ORANGE;
}
repaint();
}
}
Upvotes: 1