java JFrame设置背景颜色
初学swing,google找到youtube网上的一个教训视频,美帝的同行做的。
开发环境是apple的MAC+Eclipse.代码如下
...
JFrame f = new JFrame();
f.setSize(350,300);
f.setVisible(true);
f.setBackground(Color.RED);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
美帝的视频中,运行结果是窗口背景色是红色。
看完视频后,我在我的 windows+eclipse环境中,照打代码,
运行结果是窗口背景色是默认的白色。
百思不得淇解,又GOOGLE,在stackoverflow.com找到原因。
the area where the contents of the JFrame is being displayed is actually the "content pane", and not contents of the JFrame itself。
mainFrame.setBackground(Color.CYAN);
Is changing the color of the JFrame, but that is actually not the part which is immediately visible when the JFrame is displayed
What is needed is to change the color of what is called the "content pane* (please refer to How to Use Root Panes for an illustration), by changing the above line to the following:mainFrame.getContentPane().setBackground(Color.CYAN);
英文不是很好,大概意思是JFrame设置背景色的区域一般是看不到的。一般看到的window背景区域是JFrame里的content pane.
因此,将
f.setBackground(Color.RED);
改为
f.getContentPane().setBackground(Color.GREEN);
背景色就出来了。
出现这种差异,不找到是不同操作系统引起的,还是jdk版本的问题?
本文介绍了如何正确设置Java Swing中JFrame的背景颜色。通过对比不同的操作系统和开发环境,解释了为何直接设置JFrame背景色可能不起作用,并给出了正确的设置方法。
3179

被折叠的 条评论
为什么被折叠?



