Search code examples
javaswingjpanellayout-managerflowlayout

Java - JPanel is only one small pixel in the top center of my JFrame


The JPanel called panel only shows up as one small red square up the top center, I have tried to set the size but it doesn't seem to do anything.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;   

public class Draw extends JFrame{

private JPanel panel;

    public Draw() {
        super("title");
        setLayout(new FlowLayout());        
        panel = new JPanel();       
        panel.setBackground(Color.RED);
        add(panel, BorderLayout.CENTER);
    }
}

Solution

  • The default, preferred size of a JPanel is 0x0. FlowLayout lays out components based on their preferred size, hence the component now has a preferred size of 1x1 (the line border adds a little weight).

    You could try adding another component to panel...

    panel.add(new JLabel("This is some text"));
    

    Or override panels getPreferredSize method...

    panel = new JPanel() {
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }
    };