简体   繁体   中英

Rectangular Java Swing Radio buttons?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM