Mohamed EL Tair
Mohamed EL Tair

Reputation: 357

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);

Upvotes: 1

Views: 1916

Answers (1)

Manh Le
Manh Le

Reputation: 1650

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.setBackground(Color.red);
lbl.setOpaque(true); //Test background
getContentPane().add(pnl);

Result:

Result

Upvotes: 2

Related Questions