javaswingjlabellayout-managerborder-layout

Java swing JLabel doesn't appear in BorderLayout


I'm making 10 stars on JPanel with random location.

But the thing is when i set layout, the starts doesn't show up.

public class Main {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container c = frame.getContentPane();
    c.setLayout(new BorderLayout());

    JPanel northPanel = new JPanel(new FlowLayout());
    northPanel.add(new JButton("Open"));
    c.add(northPanel, BorderLayout.NORTH);

    JPanel southPanel = new JPanel(new FlowLayout());
    southPanel.add(new JButton("Integer Input"));
    c.add(southPanel, BorderLayout.SOUTH);

    JPanel centerPanel = new JPanel(null);
    centerPanel.setBackground(Color.pink);
    for(int i = 0; i < 10; i++) {
        int x = (int) (Math.random() * 300);
        int y = (int) (Math.random() * 300);
        JLabel label = new JLabel("*");
        label.setLocation(x, y);
        label.setForeground(Color.green);
        label.setOpaque(true);
        centerPanel.add(label);
    }
    c.add(centerPanel, BorderLayout.CENTER);

    frame.setVisible(true);
}

in the pink section, it is supposed to be shown 10 stars

enter image description here


Solution

  • I found my own way.

    after set label.setSize(10,10);

    i could find 10 stars in the panel.