0

I've tried everything in this post, but I can't seem to change the background color. What am I doing wrong so that it won't change the background color?

Main class that calls DrawGui:

public class JavaApp {
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JavaApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(JavaApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(JavaApp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(JavaApp.class.getName()).log(Level.SEVERE, null, ex);
        }

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                DrawGui.createAndShowGUI("");
            }
        });
    }
}

Gui Building class:

public class DrawGui extends JFrame {
    public DrawGui(String name) {
        super(name);
        setResizable(false);
    }

    public static void createAndShowGUI(String type) {        
        DrawGui frame = new DrawGui("Java App");

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

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.defaultMenu(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    public void defaultMenu(final Container pane) {
        JPanel infoBox = new JPanel();
        infoBox.setLayout(new GridLayout(1,2));

        infoBox.add(new Label("Benutzer: " + GlobalValues.USERNAME));
        infoBox.add(new Label("Version: " + GlobalValues.VERSION_NUMBER));

        pane.add(infoBox, BorderLayout.SOUTH);
    }
}
Community
  • 1
  • 1
RHo
  • 3
  • 3
  • 2
    Your frame has actually a red background, but the south panel has the default color, and it hides the container's color. Make your frame resizable and resize it, you will see . – Arnaud Feb 26 '16 at 14:28
  • 1
    Usually `JPanel` has an opaque background. Try setting `infoBox.setOpaque(false);`. – Olivier Grégoire Feb 26 '16 at 14:30
  • You might just want to set the infoBox background to red. – Selim Feb 26 '16 at 14:36

1 Answers1

4

There are two problems with your code right now. First, the JPanel you are adding to the content pane is opaque, which means it will block the background of the JFrame. So either set the color on it, or use setOpaque false.

If you use setOpaque, then you run into a problem where the Labels themselves are block the background. Replace them with the correct Swing component (JLabel) and that problem goes away. It's generally not a good idea to mix Swing and AWT components like this.

resueman
  • 10,572
  • 10
  • 31
  • 45