1

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);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mohamed EL Tair
  • 357
  • 1
  • 13

1 Answers1

2

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

Manh Le
  • 1,630
  • 16
  • 26
  • Yes, you need to set the JLabel to be center aligned (1+). However, there is no need for the second panel. Just add the label directly to the frame. – camickr Apr 29 '16 at 02:45