用java编写程序,单击按钮,改变框架窗口的背景色

如题,希望有相关注释
2025-03-20 13:03:56
推荐回答(2个)
回答1:

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

public class test4 {
public test4() {
final JFrame f = new JFrame();
f.setBounds(500, 200, 200, 200);
JButton jb = new JButton("颜色选择");
f.add(jb, BorderLayout.NORTH);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent cc) {
Color ch = JColorChooser.showDialog(f, "颜色选择器",
f.getBackground());
if (ch != null) {
f.getContentPane().setBackground(ch);
f.getContentPane().repaint();
}
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}

public static void main(String[] args) {
new test4();
}
}

回答2:

因为JFrame窗口,其实从下到上分为好几层:RootPane LayeredPane ContentPane GlassPane
其中最上面的GlassPane是透明的。所以设置背景色,需要设置在ContentPane上才能显示。