开发者

JLabel with separate text and icon background colours

I have a simple Jlabel element with text and icon

JLabel with separate text and icon background colours

setting the background changes the full 开发者_C百科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?

JLabel with separate text and icon background colours

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.


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜