1

I have a Gui I'm making for a program that has an outer container centered to the JFrame that contains an inner container that holds 22*12 cells. When I run this program, the background just flickers white and stays like that. If you could point me out where I'm going wrong that would be awesome!

public class Gui extends JFrame
{   
private JPanel outer, inner;
private JLabel[][] labels = new JLabel[22][12];

public Gui()
{
    setBackground(Color.black);
    setSize(1000,1000);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    outer = new JPanel();
    outer.setLayout(new BorderLayout());
    outer.setSize(620,920);
    outer.setBackground(Color.white);

    inner = new JPanel();
    inner.setLayout(new GridLayout(22,12,10,10));
    inner.setSize(600,900);
    inner.setBackground(Color.white);

    for (int i = 0; i < 22; i++)
    {
        for (int j = 0; j < 12; j++)
        {
            labels[i][j] = new JLabel();
            JLabel label = labels[i][j];
            label.setSize(50,50);
            label.setBackground(Color.gray);
            inner.add(label);
        }
    }

    outer.add(inner, BorderLayout.CENTER);
    add(outer, BorderLayout.CENTER);
    }
}

The gui is set visible in the main class that instantiates it.

The gui is created and sized correctly. It starts out with a black background then randomly turns to white just after and stays like that.

EDIT: if this is still important:

public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {

        public void run()
        {
            Gui gui = new Gui();
            gui.setVisible(true);
        }
    });
}
4

1 回答 1

5

使用遵循最终静态命名约定的新静态变量名称。那就是变量应该是大写的:

//setBackground(Color.black);
setBackground(Color.BLACK);

不要将 setSize() 用于组件。而是将组件添加到框架中,然后使用 pack() 方法,以便组件以其首选大小显示:

//setSize(1000,1000);
add(component1);
add(anotherComponent);
pack();

布局管理器使用首选大小而不是大小作为布局提示:

//label.setSize(50,50);
label.setPreferredSize(new Dimension(50, 50));

这是你的主要问题。JLabel 默认是透明的,所以你设置的背景颜色会被忽略:

label.setBackground(Color.gray);
label.setOpaque(true);

顺便说一句,我的屏幕高度只有 738,所以因为你想要 22*50 的高度,所以事件将无法看到你的整个画面。您应该意识到这一点,并可能将您的面板添加到 JScrollPane 中,以便像我这样的人可以实际使用您的应用程序。这就是为什么您不应该硬编码首选尺寸的原因。

于 2013-05-14T15:50:40.543 回答