具有单独文本和图标背景颜色的 JLabel
我有一个带有文本和图标的简单 Jlabel 元素
设置背景会更改整个标签颜色。
我希望能够仅在标签的文本部分渲染背景颜色,即 - 为图标和文本提供单独的背景/前景。选择/取消选择标签将翻转图标和文本后面的颜色。是否可以通过扩展 JLabel 来做到这一点,如果可以,我应该定制哪些方法?
我的替代想法是创建一个包含两个面板的面板单独的标签元素,一个带有图标,另一个带有文本。这看起来有点混乱,在开始之前我想知道是否有一种更智能的方法可以使用 Swing 来实现这一目标。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我喜欢你正在做的事情的风格,但看起来你正在重新实现 JToggleButton。
下面是一个切换按钮示例,左侧被选中,右侧未被选中:
alt text http:// downloads.padlocksoftware.net/toggle.png
它的文本上没有华丽的背景,但它是一个不需要您实现自己的组件的解决方案。
对齐方式设置为:
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:
我假设您使用的图标具有透明背景?如果是这样,您可以使用具有匹配背景颜色的图标。这样做应该允许您在整个标签上设置背景(),但只能在文本上看到它。
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
支持图像和文本的不同对齐选项。在大多数情况下,图像或文本都不会填充按钮的整个宽度或高度。因此,在我看来,在一个按钮中实现这一点是不现实的,除非您想覆盖按钮的绘制。您的替代想法是一个更简单的解决方案。您可以使用
BorderLayout
或MigLayout
来实现你的目标。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
orMigLayout
to achieve your goal.