emeraldjava
emeraldjava

Reputation: 11212

JLabel with separate text and icon background colours

I have a simple Jlabel element with text and icon

alt text

setting the background changes the full label colour.

I want to be able to only render the background colour on the text section of the label, ie - to have separate backgrounds/foregrounds for the icon and text. Selecting/deselecting the label will flip the colour behind the icon and text. Is this possible to do this by just extending JLabel, and if so which methods should i be looking to customise?

alt text

My alternative idea is to create a panel with two separate label elements, one with an icon the other with text. It seems a bit messy, and before i start i'm wondering is there a smarter way of achieving this with Swing.

Upvotes: 3

Views: 1259

Answers (3)

Jason Nichols
Jason Nichols

Reputation: 11753

I like the style of what you're doing, but it looks like you're reimplementing a JToggleButton.

Here is a toggle button example, with the left being selected and the right not selected:

alt text http://downloads.padlocksoftware.net/toggle.png

It doesn't have the flashy background over the text, but it's a solution that doesn't require you to implement your own component.

The alignment is set up as:

jToggleButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

Upvotes: 1

Eugene Ryzhikov
Eugene Ryzhikov

Reputation: 17369

JButton supports different alignment options for image and text. In most cases neither image or text fill the whole width or height of the button. So IMO making it happen in one button is unrealistic, unless you want to override button's painting.

Your alternative idea is a much simpler solution. There you could use BorderLayout or MigLayout to achieve your goal.

Upvotes: 0

thedude19
thedude19

Reputation: 2673

I assume the icon you're using has a transparent background? If so, you could use an icon with a matching background color. Doing this should allow you to setBackground() on the entire label but only see it on the text.

Upvotes: 0

Related Questions