Java Swing Toggle Button Example

In this post, we will learn how to create a toggle button using the JToggleButton component in swing-based applications.
Check out the complete Swing tutorial at https://www.javaguides.net/p/java-swing-tutorial.html.
JToggleButton is a button that has two states: pressed and not pressed. We toggle between these two states by clicking on it. There are situations where this functionality fits well.

Java Swing Toggle Button Example

The below example has three toggle buttons and a panel. We set the background color of the display panel to black. The toggle buttons will toggle the red, green, and blue parts of the color value. The background color will depend on which toggle buttons we have pressed:
package net.sourcecodeexamples.swingexample.components2;

import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static javax.swing.GroupLayout.Alignment.CENTER;
import static javax.swing.LayoutStyle.ComponentPlacement.UNRELATED;

public class ToggleButtonExample extends JFrame
implements ActionListener {

    private static final long serialVersionUID = 1L;
    private JToggleButton redBtn;
    private JToggleButton greenBtn;
    private JToggleButton blueBtn;
    private JPanel display;

    private void initializeUI() {

        redBtn = new JToggleButton("red");
        redBtn.addActionListener(this);

        greenBtn = new JToggleButton("green");
        greenBtn.addActionListener(this);

        blueBtn = new JToggleButton("blue");
        blueBtn.addActionListener(this);

        display = new JPanel();
        display.setPreferredSize(new Dimension(120, 120));
        display.setBorder(LineBorder.createGrayLineBorder());
        display.setBackground(Color.black);

        createLayout(redBtn, greenBtn, blueBtn, display);

        setTitle("JToggleButton");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent...arg) {

        JPanel pane = (JPanel) getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
            .addGroup(gl.createParallelGroup()
                .addComponent(arg[0])
                .addComponent(arg[1])
                .addComponent(arg[2]))
            .addPreferredGap(UNRELATED)
            .addComponent(arg[3])
        );

        gl.setVerticalGroup(gl.createParallelGroup(CENTER)
            .addGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
                .addComponent(arg[1])
                .addComponent(arg[2]))
            .addComponent(arg[3])
        );

        gl.linkSize(redBtn, greenBtn, blueBtn);

        pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        Color color = display.getBackground();

        int red = color.getRed();
        int green = color.getGreen();
        int blue = color.getBlue();

        if (e.getActionCommand().equals("red")) {
            if (red == 0) {
                red = 255;
            } else {
                red = 0;
            }
        }

        if (e.getActionCommand().equals("green")) {
            if (green == 0) {
                green = 255;
            } else {
                green = 0;
            }
        }

        if (e.getActionCommand().equals("blue")) {
            if (blue == 0) {
                blue = 255;
            } else {
                blue = 0;
            }
        }

        Color setCol = new Color(red, green, blue);
        display.setBackground(setCol);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(() -> {
            ToggleButtonExample toggleButtonExample = new ToggleButtonExample();
            toggleButtonExample.initializeUI();
            toggleButtonExample.setVisible(true);
        });
    }
}
Let's understand the above Java program.
Here we create a toggle button and set an action listener to it:
redBtn = new JToggleButton("red");
redBtn.addActionListener(this);
This is the panel that shows the color value mixed by toggle buttons. We set its preferred size (the default is very small), change the borderline to a gray color, and set the initial background color:
display = new JPanel();
display.setPreferredSize(new Dimension(120, 120));
display.setBorder(LineBorder.createGrayLineBorder());
display.setBackground(Color.black);
In the actionPerformed() method, we determine the current red, green, and blue parts of the display background color:
Color color = display.getBackground();

int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
We determine which button was toggled and update the color part of the RGB value accordingly:
if (e.getActionCommand().equals("red")) {
    if (red == 0) {
        red = 255;
    } else {
        red = 0;
    }
}
A new color is created and the display panel is updated to a new color:
Color setCol = new Color(red, green, blue);
display.setBackground(setCol);

Output

Check out the complete Swing tutorial at https://www.javaguides.net/p/java-swing-tutorial.html.

Comments