Search code examples
javaswingjframejpanelnull-layout-manager

JFrame not adding JPanel in Eclipse Neon


public class DrawablePanel extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        
        frame.setSize(500,500);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawablePanel());
        frame.setVisible(true);
    }

    public DrawablePanel(){
        setBackground(Color.black);
     }

    public Color pickColor(){
        Random rand = new Random();
        int a = rand.nextInt(255)+0;
        int b = rand.nextInt(255)+0;
        int c = rand.nextInt(255)+0;
        Color color = new Color(a,b,c);
        return color;
    }
}

I have no idea why the JPanel is not showing up on the JFrame. I have attached an image of what it looks like when I run the code.


Solution

  • frame.setLayout(null);
    

    This line removes the Layout Manager. To fix the immediate problem, just remove this line and you will get the expected black background. Then you need to learn how to use Layout Managers. The Swing API provides many options. Which one you choose depends on the look you want your program to have. I suggest checking out A Visual Guide to Layout Managers to get an overview of the most common Layout Managers.