2012-02-21 160 views
2

这可能是一个非常愚蠢的错误,但是iv'e刚刚开始学习.awt软件包。我跟着一个教程,在视频中他的窗口背景是红色的,我的代码没有错误,但它不会改变背景颜色。 感谢您的帮助!Java窗口未设置背景颜色?

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); 
    } 

} 
+0

不确定 - 但可能将setVisible移动到最后 - 那么您将获得当前设置而不必以某种方式进行刷新。 – Randy 2012-02-21 19:12:09

+0

不这样做我很害怕!这里是视频+我的小程序,以防止色盲! http://www.youtube.com/watch?v=uK2BscDZyNo&feature=relmfu http://i.imgur.com/LQMOL.png – Icy100 2012-02-21 19:14:59

回答

10

1)JFrame不能做到这一点,你必须改变Color内容窗格例如

JFrame.getContentPane().setBackground(myColor) 

2)你需要包装(在main方法)GUI相关的代码的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(); 
      } 
     }); 
    } 
} 
+0

知道了,谢谢! – Icy100 2012-02-21 19:21:34

4

代替

f.setBackground(Color.RED); 

呼叫

f.getContentPane().setBackground(Color.RED); 

内容窗格显示内容。

作为一个方面说明,这里有一个JFrame小费:你可以拨打f.add(child),这个孩子将被添加到你的内容窗格中。

+0

谢谢......我需要学会更快地回答......并在我回答时忽略我的同事:) – Paul 2012-02-21 19:31:02