Ruchir Baronia
Ruchir Baronia

Reputation: 7571

Can I highlight text in a JLabel?

I have a JLabel with some text in it. This JLabel takes up the whole bottom side of my JFrame. I have changed the background of it to yellow, and the whole bottom side becomes yellow. Is there any way to make it look like the text, which is within the JLabel, is being "highlighted" with only the text having a background color of yellow, and the rest having a different color? The top part of my JFrame is a JPanel.

combo.addItemListener(new ItemChangeListener());
JPanel container = new JPanel();
container.setBackground(Color.BLUE);

response.setFont(new Font("Times new Roman", Font.BOLD, 40));
response.setHorizontalAlignment(SwingConstants.CENTER);

response.setBackground(Color.YELLOW);
response.setOpaque(true);
add(response , BorderLayout.CENTER);
container.add(selectone);
container.add(combo);
this.add(container, BorderLayout.NORTH);

Upvotes: 1

Views: 3747

Answers (2)

RealSkeptic
RealSkeptic

Reputation: 34628

There is a very simple way to do that - use HTML in the text of the label. Mind you, Swing interprets a pretty old version of HTML, that doesn't meet today's standards.

JLabel response = new JLabel( "<html><span bgcolor=\"yellow\">This is the label text</span></html>" );

Nowadays, one should work with style sheets. But if you want to do that, you should probably switch from Swing to JavaFX.

For further details on using HTML in Swing components, see the applicable part of the tutorial.

Upvotes: 3

camickr
camickr

Reputation: 324118

Use a wrapper panel that respects the preferred size of the label:

JLabel label = new JLabel("...");
label.setOpaque( true );
label.setBackground(...);
JPanel wrapper = new JPanel();
wrapper.add( label );
frame.add(wrapper, BorderLayout.CENTER);

The default layout for a JPanel is a FlowLayout that is horizontally center aligned.

If you want both horizontal and vertical centering then use a GridBagLayout on the panel, with the default GrigBagConstraints when you add the label to the panel.

Upvotes: 3

Related Questions