🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment