Close

Java Swing - Group of Toggle Buttons (JToggleButton) for one item selection

[Updated: Jul 4, 2018, Created: Dec 28, 2017]

This example shows how to use a group of JToggleButton for one item selection. The buttons used this way act like a group of radio buttons.

Example

public class ToggleButtonsGroupExample {
  public static void main(String[] args) {
      UIManager.put("ToggleButton.select", new Color(190, 186, 164));
      JFrame frame = createFrame();
      ButtonGroup buttonGroup = new ButtonGroup();
      JPanel buttonPanel = new JPanel();
      ActionListener listener = actionEvent ->
              System.out.println(actionEvent.getActionCommand() + " Selected");
      for (int i = 0; i < 5; i++) {
          JToggleButton b = new JToggleButton(Integer.toString(i + 1));
          b.addActionListener(listener);
          buttonGroup.add(b);
          buttonPanel.add(b);
      }
      frame.add(buttonPanel, BorderLayout.NORTH);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JToggleButton Group example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(600, 300));
      return frame;
  }
}

Output

Console output on button selections:

3 Selected
5 Selected
1 Selected
3 Selected

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

JToggleButton Group Example Select All Download
  • toggle-button-group-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ToggleButtonsGroupExample.java

    See Also