Turn Desktop View Off
by Dinesh Thakur

Swing provides a variant of push button called toggle button which has two states: pushed and released. When toggle button is pressed for the first time, it remains pressed and it is released only when it is pressed for the second time. This button toggles between pushed and released state. Toggle button is an object of JToggleButton class.

Some of the constructors defined by JToggleButton class are as follows.

JToggleButton ()

JToggleButton(String string)

JToggleButton(String string, boolean state)

where,

string specifies the text

state can have one of the two values: true, if the button is initially selected, otherwise false (default value)

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
public class JavaExampleToggleInJApplet extends JApplet
{
    public JavaExampleToggleInJApplet()
    {
        Container Cntnr = getContentPane();
        Icon Icn = new ImageIcon("Koala.jpg");
        JToggleButton TglOne = new JToggleButton(Icn);
        JToggleButton TglTwo = new JToggleButton(Icn, true);
        JToggleButton TglThree = new JToggleButton("Toggle It!");
        JToggleButton TglFour = new JToggleButton("Toggle It!", Icn);
        JToggleButton TglFive = new JToggleButton("Toggle It!",Icn,true);
        Cntnr.setLayout(new FlowLayout());
        Cntnr.add(TglOne);
        Cntnr.add(TglTwo);
        Cntnr.add(TglThree);
        Cntnr.add(TglFour);
        Cntnr.add(TglFive);
    }
}
/*<APPLET CODE=JavaExampleToggleInJApplet.class WIDTH=400 HEIGHT=400> </APPLET>*/

JToggleButton Java Example