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.

Rom1
  • 3,167
  • 2
  • 22
  • 39
Nick Fortescue
  • 43,045
  • 26
  • 106
  • 134

2 Answers2

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.

Rom1
  • 3,167
  • 2
  • 22
  • 39
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

ignis
  • 8,692
  • 2
  • 23
  • 20
  • Sorry, this isn't what I was looking for - you still get the small circle, and the extra space used. – Nick Fortescue Jun 02 '11 at 08:09
  • 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. :) – ignis Jun 02 '11 at 17:15