- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we implement a JToggleButton in Java?
JToggleButton
- A JToggleButton is an extension of AbstractButton and it can be used to represent buttons that can be toggled ON and OFF.
- When JToggleButton is pressed for the first time, it remains pressed and it can be released only when it is pressed for the second time.
- A JToggleButton generates an ActionEvent each time it is pressed.
- A JToggleButton can also generate an ItemEvent, this event is used by those components that support the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is deselected.
- To handle item events, you must implement the ItemListener interface. This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. A toggle button’s state is by calling the isSelected( ) method on the button that generated the event.
Example
import javax.swing.*; import java.awt.*; import java.awt.event.*; class JToggleButtonTest extends JFrame implements ItemListener { private JToggleButton jtb; JToggleButtonTest() { setTitle("JToggleButton Test"); setLayout(new FlowLayout()); setJToggleButton(); setAction(); setSize(450, 300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private void setJToggleButton() { jtb = new JToggleButton("ON"); add(jtb); } private void setAction() { jtb.addItemListener(this); } public void itemStateChanged(ItemEvent eve) { if(jtb.isSelected()) jtb.setText("OFF"); else jtb.setText("ON"); } } public class MainApp { public static void main(String[] args) { new JToggleButtonTest(); } }
Output
- Related Articles
- How can we implement a timer thread in Java?
- How can we implement a Custom HashSet in Java?
- How can we implement a custom iterable in Java?
- How can we implement a scrollable JPanel in Java?
- How can we implement a rounded JTextField in Java?
- How can we implement transparent JDialog in Java?
- How can we implement editable JComboBox in Java?
- How can we Implement a Stack using Queue in Java?
- How can we implement a map in JShell in Java 9?
- How can we Implement a Queue using Stack in Java?\n
- How can we implement a moving text using a JLabel in Java?
- How can we implement auto-complete JComboBox in Java?\n
- How can we implement an editable JLabel in Java?\n
- How can we implement the SubmissionPublisher class in Java 9?
- How can we implement the Subscriber interface in Java 9?

Advertisements