Search code examples
javaswinguser-interfacejbuttonactionlistener

Making 1 single JButton change panel background


Quick question how would you make 1 JButton change the color of the panel when clicked and displays what color it is I've done some tutorials having 3 JButtons color change when a different button is clicked but how you make just one JButton change the panel color for example yellow, green, and red.

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

   public class ChangeButtonColor{
   JButton button;
   public static void main(String[] args){
   ChangeButtonColor cl = new ChangeButtonColor();
  }

   public ChangeButtonColor(){
      JFrame frame = new JFrame("Change JButton Color");
      JPanel panel = new JPanel();
      button = new JButton();
      button.addActionListener(new MyAction());
      frame.add(button);
      frame.setSize(400, 400);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }

  public class MyAction implements ActionListener{
  public void actionPerformed(ActionEvent e){


   }
 }
}

Solution

  • "maybe i could do for example when the button is clicked (if panel color is red print out red , else if panel is green print out green) would that be good"

    You can just check if (panel.getBackground() == Color.RED), for example

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class ColorClick {
    
        public static void main(String[] args) {
            final JPanel panel = new JPanel(new GridBagLayout()) {
                {
                    setBackground(Color.RED);
                }
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(200, 200);
                }
            };
            JButton button = new JButton("Change Color");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (panel.getBackground() == Color.RED) {
                        System.out.println("RED");
                        panel.setBackground(Color.GREEN);
                    } else if (panel.getBackground() == Color.GREEN) {
                        System.out.println("GREEN");
                        panel.setBackground(Color.RED);
                    }
                }
            });
            panel.add(button);
            JOptionPane.showMessageDialog(null, panel);
        }
    }