dvas89
dvas89

Reputation: 25

Change JFrame background color with JButton not updating

I'm trying to make a very simple GUI that updates the background color upon clicking a button. I can't for the life of me figure out what is wrong with my code. When it is run nothing updates upon clicking the buttons, any help would be appreciated!

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class ChallengeGUI extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private JButton blue;
    private JButton red;
    private JButton green;


    public ChallengeGUI() {

        JButton blue = new JButton("BLUE");
        blue.addActionListener(this);
        add(blue);

        JButton red = new JButton("RED");
        red.addActionListener(this);
        add(red);

        JButton green = new JButton("GREEN");
        green.addActionListener(this);
        add(green);

        setLayout(new FlowLayout());
        setSize(600,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == blue) {
            getContentPane().setBackground(Color.BLUE);
        } else if (e.getSource() == red) {
            getContentPane().setBackground(Color.RED);
        } else if (e.getSource() == green) {
            getContentPane().setBackground(Color.GREEN);
        }

    }

    public static void main(String[] args) {
        new ChallengeGUI();

    }

}

Upvotes: 0

Views: 141

Answers (2)

matt
matt

Reputation: 12346

You have one mistake.

  • You've shadowed your buttons so e.getSource()==red is always false.

Instead of

JButton red = new JButton("RED");

just write

red = new JButton("RED");

When you wrote: JButton red = ... it created a local variable named red separate from the field declared in your class, also named red. That means the field did not get initialized. In your listener, none of the cases were true because red, blue, and green were null and e.getSource() was returning the local JButton you created.

Upvotes: 2

Abra
Abra

Reputation: 20924

You can write your actionPerformed() method like this:

public void actionPerformed(ActionEvent e) {
    String actionCommand = e.getActionCommand();
    Color color;
    switch (actionCommand) {
        case "BLUE":
            color = Color.BLUE;
            break;
        case "RED":
            color = Color.RED;
            break;
        case "GREEN":
            color = Color.GREEN;
            break;
        default:
            color = null;
            JOptionPane.showMessageDialog(null, "Unhandled: " + actionCommand);
    }
    if (color != null) {
        getContentPane().setBackground(color);
    }
}

Upvotes: 0

Related Questions