Search code examples
javaswinglayoutjlabelborder-layout

How to add two label with preferred size to a panel by using BorderLayout?


I am trying to add to label to north and south of a panel and add the panel to the centre of my frame. If I don't specify the size of the labels by myself the program is perfect but when I give them specific dimension:

label.setPreferredSize(di);
label2.setPreferredSize(di);

it gets messy! However the size of panel and frame are larger and (100,100) Any idea?

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;


import javax.swing.JFrame;

public class BorderLayoutDemo2 {

    public static void main(String args[])
    {
        Frame frame = new Frame();
    }
}

class Frame extends JFrame
{

    private static final long serialVersionUID = 1L;

    public Frame(){
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension di = new Dimension(50,50);
        Dimension dim = new Dimension(200,200);

        JPanel panel = new JPanel();
        panel.setPreferredSize(dim);

        JLabel label = new JLabel("Here is my label");
        JLabel label2 = new JLabel("Here is my label2");



        JMenuBar menu = new JMenuBar();
        JMenu setting = new JMenu("Setting");
        JMenuItem exit = new JMenuItem("Exit");
        JMenuItem add = new JMenuItem("Add");
        setting.add(add);
        setting.add(exit);
        menu.add(setting);

        label.setPreferredSize(di);
        label2.setPreferredSize(di);

        panel.add(label,BorderLayout.NORTH);
        panel.add(label2,BorderLayout.SOUTH);

        add(menu,BorderLayout.NORTH);
        add(panel,BorderLayout.CENTER);


        pack();
        setVisible(true);
    }

}

Solution

  • You are assuming the layout of the panel is BorderLayout when you add components, ie: panel.add(label,BorderLayout.NORTH);. But you are not setting the layout and JPanel uses FlowLayout which is its default. You can fix it like this:

    JPanel panel = new JPanel(new BorderLayout());