Mohamed EL Tair Mohamed EL Tair - 2 years ago 87
Java Question

Adding a label to the center south of a panel?

The code below adds the label to the left south of the panel, and when I use set location with the label, the position does not change. Is there a way to make the label be in the center south of the panel without the need for an extra panel?

EDIT: the JFrame has a BorderLayout and adds the panel to CENTER

JPanel pnl = new JPanel();
pnl.setPreferredSize(new Dimension(500,500));
JLabel lbl = new JLabel("label");
pnl.setLayout(new BorderLayout());
pnl.add(lbl, BorderLayout.SOUTH);

Answer Source

It seem you need to set text align of label to center panel? If so, try this:

JPanel pnl = new JPanel();
pnl.setPreferredSize(new Dimension(500, 500));
JLabel lbl = new JLabel("label", SwingConstants.CENTER); //Set text align
pnl.setLayout(new BorderLayout());
pnl.add(lbl, BorderLayout.SOUTH);
lbl.setOpaque(true); //Test background



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download