制作1个单独的JButton更改面板背景

时间:2014-03-31 15:40:55

标签: java swing user-interface jbutton actionlistener

快速提问如何点击1 JButton更改面板的颜色并显示它的颜色我点击了一个不同的按钮后,我做了一些教程有3 JButtons颜色变化但是你如何只用一个JButton来改变面板颜色,例如黄色,绿色和红色。

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){


   }
 }
}

1 个答案:

答案 0 :(得分:2)

  

“也许我可以这样做,例如当点击按钮时(如果面板颜色是红色打印出红色,否则如果面板是绿色打印出绿色)那将是好的”

您只需检查if (panel.getBackground() == Color.RED),例如

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);
    }
}