[英]Can't change background color of JFrame or JPanel
我无法让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);
}
编辑:添加了代码工作的图片插图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.