Search code examples
javaswingjbuttonjapplet

Giving one JButton two different actions


I am very new to java and not aware of the methods I can use to achieve what I'm trying to do. I need to make a program that simulates a light switch. One button that turns the light on and off. I set the background colour to dark gray before the event is fired and after fired the background color is set to yellow. The problem I have is when the background is yellow how can I change it back to dark gray using the same button?

My code:

import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Question2 extends JApplet implements ActionListener {
    public void init() {
        Container contentPane = getContentPane();
        contentPane.setBackground(Color.DARK_GRAY);

        contentPane.setLayout(new FlowLayout());

        JButton OnOffSwitch = new JButton("On/Off");
        contentPane.add(OnOffSwitch);
        OnOffSwitch.addActionListener(this);    
    }

    public void actionPerformed(ActionEvent e) {
        Container contentPane = getContentPane();

        if (e.getActionCommand().equals("On/Off"))
            contentPane.setBackground(Color.YELLOW);
        else 
            contentPane.setBackground(Color.DARK_GRAY);
    }
}

Solution

  • Have a boolean field called on set to false

    boolean on = false;
    

    and in your actionPerformed have a flip logic something like this

    public void actionPerformed(ActionEvent e)
    {
        Container contentPane = getContentPane();
    
        if (!on) {
                contentPane.setBackground(Color.YELLOW);
                on = true;
        }
        else  {
            contentPane.setBackground(Color.DARK_GRAY);
            on = false;
        }
    }