如何将 JFrame 的背景颜色设置为其空白值?

How to set the background color of JFrame to its blank value?

我想在使用 'color' 按钮为背景添加颜色后,使用 'Clear' 按钮清除 JFrame 的背景颜色。我能找到的所有内容都告诉我如何将值更改为不同的颜色,但没有告诉我如何删除它。

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

public class ColorFrame extends JFrame {
    JButton red, green, blue, clear;
    
    public ColorFrame() {
        super("ColorFrame");
        
        setSize(322, 122);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout(); 
        setLayout(flo);
        red = new JButton ("Red");
        add(red);
        green = new JButton ("Green");
        add(green);
        blue = new JButton("Blue");
        add(blue);
        clear = new JButton("Clear");
        add(clear);
    
        ActionListener act = new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                if(event.getSource() == red) {
                    getContentPane().setBackground(Color.RED);
                }
                if(event.getSource() == green) {
                    getContentPane().setBackground(Color.GREEN);
                }
                if(event.getSource() == blue) {
                    getContentPane().setBackground(Color.BLUE);
                }   
                if(event.getSource() == clear) {
                    //clear background color
                }
            }
        };

        red.addActionListener(act);
        green.addActionListener(act);
        blue.addActionListener(act);
        clear.addActionListener(act);

        setVisible(true);
    }
    public static void main(String arguments[]) {
        new ColorFrame();
    }
}

将背景设置为无颜色,即空:

getContentPane().setBackground(null);

"我能找到的一切都告诉我如何将值更改为不同的颜色,但没有告诉我如何删除它。" - 这是因为你不应该吨。即使是“默认”背景颜色也是一种颜色,我认为您不应该尝试以任何方式“删除”它。

您当然可以将 JFrame(或更具体地说,框架的内容窗格)的背景颜色设置回其默认值。 为此,您可以使用以下两种方法之一:

1.修改前只需保存默认值

public class ColorFrame extends JFrame {
    JButton red, green, blue, clear;
    Color defaultColor;

    ...

    ActionListener yourListener = new ActionListener() {
        public void actionPerformed (ActionEvent event) {
            // save the frame background default value before changing it
            defaultColor = getContentPane().getBackground();
            // modify the color as needed and use the stored default later as needed

2。从 UIManager

中检索默认背景颜色

每个 swing 组件的默认属性都存储在 UIManager 中,具体到每个外观和感觉。了解这一点,您可以根据需要轻松检索这些默认值:

Color defaultColor = UIManager.getColor("Panel.background");
getContentPane().setBackground(defaultColor);

关于您的代码的一些额外注意事项:

  • 使用 Action 或至少分开 ActionListener 如果您希望每个按钮有不同的行为。不推荐共享 ActionListener 然后检查从哪个组件触发操作。
  • 不要使用 setSize()。相反,让 LayoutManager 在添加所有组件后通过在 JFrame 上调用 pack() 来为您调整组件和框架的大小。
  • 如无必要,请避免扩展 JFrame。 (我目前认为您的代码中没有必要这样做,因为您没有从根本上更改 JFrame 的默认行为)