Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java Tip 142: Pushing JButtonGroup

Build a better ButtonGroup

  • Print
  • Feedback

Page 3 of 3

public AbstractButton getButton(ButtonModel model)
{
  Iterator it = buttons.iterator();
  while (it.hasNext())
  {
    AbstractButton ab = (AbstractButton)it.next();
    if (ab.getModel() == model) return ab;
  }
  return null;
}


getSelected() and isSelected() are the simplest and probably most useful methods of the JButtonGroup class. getSelected() returns a reference to the selected button, and isSelected() overloads the method of the same name in ButtonGroup to take a button reference:

public AbstractButton getSelected()
{
  return selectedButton;
}
public boolean isSelected(AbstractButton button)
{
  return button == selectedButton;
}


This method checks whether a button is part of the group:

public boolean contains(AbstractButton button)
{
  return buttons.contains(button);
}


You would expect a method named getButtons() in a ButtonGroup class. It returns an immutable list containing references to the buttons in the group. The immutable list prevents button addition or removal without going through the button group's methods. getElements() in ButtonGroup not only has a totally uninspired name, but it returns an Enumeration, which is an obsolete class you shouldn't use. The Collections Framework provides everything you need to avoid enumerations. This is how getButtons() returns an immutable list:

public List getButtons()
{
  return Collections.unmodifiableList(buttons);
}


Improve ButtonGroup

The JButtonGroup class offers a better and more convenient alternative to the Swing ButtonGroup class, while preserving all of the superclass's functionality.

About the author

Daniel Tofan is as a postdoctoral associate in the Chemistry Department at State University of New York, Stony Brook. His work involves developing the core part of a course management system with application in chemistry. He is a Sun Certified Programmer for the Java 2 Platform and holds a PhD in chemistry.

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources