我无法让 JPanel 改变颜色。我也无法让 JFrame 改变颜色。我在网上查看过...我有另一个程序,它具有几乎相同的用于设置 JPanel 和 JFrame 的代码。我就是无法让它发挥作用。
这是我的主要方法:
public static void main(String[] args){
JFrame frame = new JFrame("title");
frame.getContentPane().setBackground(Color.WHITE);
Drawing drawing = new Drawing(2);
drawing.setBackground(Color.CYAN);
frame.add(drawing);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
...
编辑:稍后在我的主要方法中是
frame.setLocationRelativeTo(null);
frame.setVisible(true);
这是 JPanel 的构造函数:
public class Drawing extends JPanel {
// instance variables
public Drawing(int n){
setOpaque(true);
setPreferredSize(new Dimension(300, 300));
setBackground(Color.PINK);
...
背景颜色保持默认灰色。
最佳答案
我在使用 Eclipse 制作快速窗口构建器应用程序以及设置颜色时没有遇到任何问题。
我注意到的一些事情是您执行的是 frame.add(drawing)
而不是 frame.getContentPane().add(drawing)
。
您也永远不会使用 frame.setVisible(true)
将框架设置为可见。
这是我使用的代码:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.GREEN);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.CYAN);
panel.setBounds(10, 171, 128, 81);
frame.getContentPane().add(panel);
}
编辑:添加了代码工作的图片说明
关于java - 无法更改 JFrame 或 JPanel 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036843/