我想使用'Clear'按钮来清除JFrame
的背景颜色,然后使用'color'按钮为背景添加颜色。我所能找到的一切都告诉我如何将值更改为不同的颜色,但不告诉我如何删除它。
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();
}
}
">我所能找到的一切都告诉我如何将值更改为不同的颜色,但不知道如何删除它。"-这是因为你不应该。即使是"默认"背景色是一种颜色,我认为你不应该试图"移除"。
当然,您可以将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
s或至少单独的ActionListener
s。不建议使用共享的ActionListener
来检查动作是从哪个组件触发的。 - 不要使用
setSize()
。相反,在添加所有组件后,让LayoutManager
在JFrame
上调用pack()
来为您调整组件和框架的大小。 - 如果没有必要,避免扩展
JFrame
。(我目前认为没有必要在你的代码,因为你没有从根本上改变JFrame
的默认行为)
设置背景为无颜色,即null:
getContentPane().setBackground(null);