简体   繁体   English

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

[英]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. 快速问题如何使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){


   }
 }
}

"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 例如,您可以检查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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM