I'm working on my personal Java chat client whose one feature is setting user's status (Available, Invisible, Busy). To make it user-friendly, I put those statuses into a JMenu
with JRadioButtonMenuItem
.
The problem is I want each status RadioButton
to have its own radio-dot color (or dot-icon). For example:
- [Green-Dot] Available
- [Red-Dot] Busy
- [Gray-Dot] Invisible.
I thought of extending the JRadioButtonMenuItem
with three different custom RadioButtonMenuItem
, but couldn't understand how JRadioButtonMenuItem
is painted.
Could anyone help me to solve this problem?
Edit 1
Thanks for your suggestions to use Icon
together with setIcon()
and setSelectedIcon()
methods.
However since my question is about changing the radio-dot, could you also help me to hide the radio-dot from a RadioButton
?
Edit 2
Here's the current screenshot of my app.
As you can see the dot before that RadioButtonMenuItem
is somehow ridiculously nonsense. That's why I want to get rid of the dot, or change it to my custom icon :)
I suggest you use the Icon property of Swing Components. Here is example which sets an icon to the JRadioButtonMenuItem. Whenever there is a change in status use seticon method to change the icon. Instead of colors use icons
Here's an Example http://www.java2s.com/Code/Java/Swing-JFC/Anexampleofradiobuttonmenuitemsinaction.htm
My thought was, the behavior of the JRadioButtonMenuItem is fine, it's just its painting is a little goofy. But I don't want to have to extend it or override paint or any of those shenanigans. So I concluded, just steal its behavior and leave its painting behind.
You'll notice that
ButtonGroup
acceptsAbstractButton
s, so I like dungeon Hunter's solution: use regularJMenuItem
s. I'd append to that, steal theJToggleButton
'sButtonModel
and send in anItemListener
that will do the image swapping (as Ramesh John suggested).And this'll work for any old icon, not just changing the button's color.
The radio button's dot is rendered by the UI delegate for each Look & Feel. You can supply your own
BasicRadioButtonUI
, but the effort is not trivial. As an alternative, implement theIcon
interface, as shown here inColorIcon
.Add a new class to customize the
RadioButtonMenuItem
by extendingJRadioButtonMenuItem
.Add inner class to update status Icon by implementing Icon inteface. Override all the methods update the
paintIcon()
method with current status icon.Call super class by passing status icon.
Add listner to get the latest event to update the Icon using
setIcon()
method.