BorderLayout.CENTER doesn't center

JohnND picture JohnND · Jun 6, 2013 · Viewed 22.1k times · Source

I can't get my JLabel to center in my JPanel after adding a ChartPanel to it:

JPanel panel = new JPanel(new BorderLayout());            
panel.add(visualiser(ternaire), BorderLayout.NORTH);//visualiser(ternaire) is the ChartPanel
panel.add(new JLabel("L'alliage a bien été enregistré."), BorderLayout.CENTER);
JOptionPane jop = new JOptionPane();            
jop.showMessageDialog(null, panel, "Information", JOptionPane.PLAIN_MESSAGE);

Any idea why BorderLayout.CENTER doesn't work ?

Answer

MadProgrammer picture MadProgrammer · Jun 6, 2013

JLabel by default is horizontally aligned to the left.

You need to set the horizontalAlignment to be JLabel.CENTER

JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("L'alliage a bien été enregistré.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
panel.add(label, BorderLayout.CENTER);