views:

180

answers:

3

Hey,

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.

A: 

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.

thedude19
Yep - using transparent icons for selected and deselected actions. The whole idea here is to avoid having to regenerate or change icon colours. I know i can hack it but i'm looking for the correct solution.
emeraldjava
A: 

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.

eugener
+1  A: 

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

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);
Jason Nichols
And has better styling too!
XpiritO