Rectangular Java Swing Radio buttons?
Asked Answered
P

2

5

I'd like to create a set of buttons in a Java Swing application like you get in a typical tool palette in a paint program. That is, a set of small square buttons, each containing an icon, only one of which is pressed down, and when you press another button, the first is deselected. I've thought of a number of solutions and none of them seem very easy/elegant.

This sounds like a job for JRadioButton, but if you add an Icon to that, you still get the small circle, which is fairly space inefficient. I guess an option would be finding an alternative Look and Feel or painting code for JRadioButton.

Another alternative might be to add JButton to a ButtonGroup, maybe setting a JToggleButton.ToggleButtonModel as the model, but that doesn't have the desired effect, as the painting code for a standard JButton does not keep it depressed when selected. Possibly the JButton code could be modified to do this. Like making it painting "selected" the same way as "pressed".

A third alternative would be to use normal JButton's, and add a common mouse listener that keeps them pressed or not, and communicates the changes between the buttons.

Can anyone advise on the best way to achieve the aim please? A simple method I've missed would be best, but advice on which of these three alternatives would be best and pointers on how to get started would be useful too.

Peradventure answered 1/6, 2011 at 17:7 Comment(0)
A
9

What about a plain JToggleButton in a ButtonGroup? It is not abstract, you can instantiate one with an Icon, and it stays depressed while selected.

Aussie answered 1/6, 2011 at 17:13 Comment(2)
From the Swing tutorial:"JToggleButton can be useful when you do not want the typical radio button or check box appearance."Lupus
Perfect, thank you. I thought there would be something easy I'd missed.Peradventure
A
1

See the SwingSet2 demo: http://java.sun.com/products/plugin/1.4/demos/jfc/SwingSet2/SwingSet2.html

Click the second icon on the toolbar (the one twith the check box and radio button) then tab "Radio buttons". Then click on "Paint Border" on the right panel, under "Display Options".

Source code of the demo is under your JDK install dir, so for example on my PC it's under \jdk1.6.0_01\demo\jfc\SwingSet2\src

Araarab answered 1/6, 2011 at 17:28 Comment(2)
Sorry, this isn't what I was looking for - you still get the small circle, and the extra space used.Peradventure
Actually I think it really is what you are looking for. The circles under "image radio buttons" are custom images - that is, you may replace them with squares or pineapples if you want, in which case you would get no small circle. Then you may setText("") or setText(null) on the radio button. :)Araarab

© 2022 - 2024 — McMap. All rights reserved.