Search code examples
javahtmlswinglayout-managergridbaglayout

How do you set a JLabel to take all the available width space?


I'm trying to center the JLabel text and to change the background and foreground color. I tried to use HTML:

JLabel listHeader = new JLabel("<html><span style='background-color:#555;color:White;text-align:center;'>Tables</span></html>"); 

But it doesn't seem to work as you can see in the image below.

Image of the components

The label is inside a panel that has the layout manager set to grid bag layout with the following constraints:

c.gridy=0;
c.gridx=0;
c.weighty=0;
c.weightx=1;
c.fill=GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;

I tried with fill BOTH as well, same result.

How can I make the label take all the width space?


Solution

  • You could try to anchor at the center, not on the start of the line.