Java GUI编程:设置前景/背景

3

我刚开始学习GUI编程,进展缓慢。

然而,我一开始就遇到了一个问题。我无法改变窗口的前/背景颜色。

但是,当我通过JLabel添加标签,然后使用setFore/Back时,它们的颜色可以很好地改变。只是整个窗口不行。

我认为.setForeground和.setBackground应该能够改变窗口的颜色吧?

import javax.swing.*;
import java.awt.*;

public class MyWindow {

    public static void main(String args[])
    {
         Runnable init = new Runnable()
         {
             public void run()
             {

                    JFrame myWindow = new JFrame("Hola!");
                    myWindow.setForeground(Color.YELLOW);
                    myWindow.setBackground(Color.YELLOW);
                    myWindow.setSize(400, 300);

                    myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    myWindow.setLayout(null);

                    myWindow.setVisible(true);

             }

         };
         SwingUtilities.invokeLater(init);
    }


}
3个回答

9

首先,不要使用空布局。让布局管理器完成它的工作。其次,你需要为JFrame实例的内容窗格设置背景,如下所示:

myWindow.getContentPane().setBackground(Color.YELLOW);

另请参阅:


这里有各种Swing层的解释,可能有助于解释这种行为:http://download.oracle.com/javase/tutorial/uiswing/components/toplevel.html - Sean

3

你不能给框架着色。但是你可以给里面的ContentPane着色。

import javax.swing.*;
import java.awt.*;

    public class MyWindow {

        public static void main(String args[])
        {
             Runnable init = new Runnable()
             {
                 public void run()
                 {

                        JFrame myWindow = new JFrame("Hola!");

    myWindow.getContentPane().setBackground(Color.YELLOW);

                        myWindow.setSize(400, 300);

                        myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        myWindow.setLayout(null);

                        myWindow.setVisible(true);

                 }

             };
             SwingUtilities.invokeLater(init);
        }  
    }

这应该能解决你的问题...


-1

唐纳·纳曼,这个人太蠢了,pokegooo

import javax.swing.; import java.awt.;

public class MyWindow {

    public static void main(String args[])
    {
         Runnable init = new Runnable()
         {
             public void run()
             {

                    JFrame myWindow = new JFrame("Hola!");

myWindow.getContentPane().setBackground(Color.YELLOW);

                    myWindow.setSize(400, 300);

                    myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    myWindow.setLayout(null);

                    myWindow.setVisible(true);

             }

         };
         SwingUtilities.invokeLater(init);
    }  
}

// 先停一下,等一下再继续 // 张开


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接