Search code examples
javaswingbackgroundopacityjlabel

swing gui flickering white error


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

Solution

  • Use the new static variable names which follow final static naming convention. That is the variable should be upper cased:

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

    Don't use setSize() for components. Instead add the components to the frame and then use the pack() method so the components are displayed at their preferred size:

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

    Layout managers use the preferred size not the size as a layout tip:

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

    This is your main problem. A JLabel is transparent by default, so the background color you set is ignored:

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

    By the way, my screen height is only 738, so won't event be able to see you entire frame since you want a height of 22*50. You should be aware of this and probably add your panel to a JScrollPane so people like me can actually use your application. This is why you should not hardcode a preferred size.