JFrame在使用“顏色”按鈕為背景添加顏色后,我想使用“清除”按鈕清除 a 的背景顏色。我能找到的一切都告訴我如何將值更改為不同的顏色,但沒有告訴我如何洗掉它。
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();
}
}
uj5u.com熱心網友回復:
“我能找到的一切都告訴我如何將值更改為不同的顏色,但沒有告訴我如何將其洗掉。 ” - 這是因為您不應該這樣做。即使“默認”背景顏色也是一種顏色,我認為您不應該嘗試以任何方式“洗掉”它。
您當然可以將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);
關于您的代碼的一些其他注意事項:
- 如果您希望每個按鈕的行為不同,請使用
Actions 或至少使用單獨的ActionListeners。ActionListener不建議使用共享然后檢查操作是從哪個組件觸發的。 - 不要使用
setSize(). 相反,LayoutManager通過在添加所有組件后呼叫pack()來為您調整組件和框架的大小JFrame。 JFrame如果沒有必要,請避免擴展。(我目前認為不需要在您的代碼中,因為您沒有從根本上更改 的默認行為JFrame)
uj5u.com熱心網友回復:
將背景設定為無顏色,即空:
getContentPane().setBackground(null);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326954.html
