JToggleButton in Java with Example


JToggleButton in Java with Example

beginning with programming logo

Table of Contents
a) Introduction to JToggleButton
b) Example with Source Code
c) Ouput
*********************
Introduction


JToggleButton is the Swing components which are used to create a toggle button. Toggle button is a component like button however, it has two distinct state i.e pressed (on state) and released (off state). For example, the electric bulb or fan or some electronic things there are two states either ‘on’ or ‘off’. In a same manner toggle button is used. It can be used as switch.  JToggleButton generates the Item Event every time when the button is clicked.

isSelected() method is used in toggle button because it returns the true or false value. When the button is clicked then it returns true otherwise it returns false.

Let us see the example of toggle button with source code and output.

Source Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package JToggle;

/**
 *
 * @author AnkitPC
 */
import java.awt.*; // for layout
import java.awt.event.*; // for event
import javax.swing.*; // for components
public class JToggleButtonDemo implements ItemListener {
    JFrame f;
    JToggleButton b;
    // constructor
    JToggleButtonDemo(){
        f=new JFrame("Toggle Button Demo");
        // set size of the frame
        f.setSize(400,300);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // setting layout
        f.setLayout(new FlowLayout());
    
        b=new JToggleButton("On");
        // registering the event
        b.addItemListener(this);
        // adding button to the frame
        f.add(b);
       
        f.setVisible(true);
       
       
    }
    // main method
    public static void main(String[] args) {

        // call constructor
       new JToggleButtonDemo();
       
    }

    // performing some actions
    public void itemStateChanged(ItemEvent e){
        if(b.isSelected()){
            b.setText("Off");
           
        }
        else{
            b.setText("On");
        }
    } 
}

Note: The highlighted words are the comments.

Output:
jtogglebutton in java
As I said earlier it works as a switch. If it is clicked then it will remain in the same state until and unless another click is not done to the button. The image below shows the output where the button is pressed ‘on’. It remains infinitely if we don’t click the button again.
jtogglebutton in java

Now I have clicked the button and now it is showing ‘off’ state.

****************

Previous Lessons;
JTabbedPane in Java


Post a Comment

0 Comments