Reputation: 57
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.
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?
Upvotes: 1
Views: 1472
Reputation: 324098
I tried to use HTML:
Don't use HTML.
I'm trying to center the JLabel text
To center the text in the space available to the label you can use:
label.setHorizontalAlignment(JLabel.CENTER);
and to change the background and foreground color.
You need to make the label opaque:
label.setOpaque( true ):
label.setBackground( Color.RED );
I tried with fill BOTH as well, same result.
Well, I don't think you want "BOTH" since you are only concerned with the width. You may also need to use the weightx
constraint. Read the section from the Swing tutorial on How to Use GridBagLayout for more information on using the constraints.
Without your MCVE/SSCCE
we can't see exactly what you are doing.
Upvotes: 1
Reputation: 397
You could try to anchor at the center, not on the start of the line.
Upvotes: 0