Java窗口没有设置背景颜色?
这可能是一个非常愚蠢的错误,但我只是开始学习.awt包。 我按照教程写了一封信,在video中他的窗口背景为红色,我的代码中没有错误但它不会改变背景颜色。 谢谢你的帮助!
import java.awt.Color; import javax.swing.*; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub JFrame f = new JFrame(); f.setVisible(true); f.setSize(350,350); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Window"); f.setBackground(Color.RED); } }
1) JFrame
无法做到这一点,您必须更改内容窗格的Color
,例如
JFrame.getContentPane().setBackground(myColor)
2)您需要将GUI相关代码(在main
方法中)包装到invokeLater
例如:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GUI { public GUI() { JFrame frame = new JFrame(); frame.setTitle("Test Background"); frame.setLocation(200, 100); frame.setSize(600, 400); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().setBackground(Color.BLUE); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { GUI gUI = new GUI(); } }); } }
代替
f.setBackground(Color.RED);
呼叫
f.getContentPane().setBackground(Color.RED);
内容窗格显示的内容。
作为旁注,这里是一个JFrame
提示:您可以调用f.add(child)
,孩子将被添加到内容窗格中。