JLabel with separate text and icon background colours

I have a simple Jlabel element with text and icon

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?

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.

链接地址: http://www.djcxy.com/p/67654.html

上一篇: 如何将鼠标监听器添加到嵌入在JLabel中的ImageIcon中?

下一篇: JLabel具有单独的文本和图标背景颜色