Tuesday 18 October 2016

JToggleButton



*      A toggle button is just like a push button, but it is different because it has two states: pushed and released. That is, when we press a toggle button, it stays pressed rather than popping back up as a rectangular push button does. When we press the toggle button a second time, it releases (pops up).
*      JToggleButton implements AbstractButton. JToggleButton is a superclass for two other Swing components that also represent two-state control: JCheckBox and JRadioButton.
*      One of the widely used constructor for JToggleButton is as follows:
JToggleButton(String str)
Here, a toggle button is created that contains the string str.
*      By default the button is in off position. JToggleButton uses a model defined by a nested class called JToggleButton.ToggleButtonModel.
*      Like JButton, JToggleButton generates an action event each time it is pressed.
*      Unlike JButton, JToggleButton also generates an item event. This event is used by those components that support the concept of selection.
*      The easiest way to determine a toggle button’s state is by calling the isSelected() method on the button that generated the event.
boolean isSelected()
It returns true if the button is selected otherwise false.
*      Example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyToggleButton extends JApplet
{
  JLabel l1;
  JToggleButton jb;
  public void init()
  {
   try
   {
    SwingUtilities.invokeAndWait(new Runnable() {
      public void run()
      {
          makeGUI();
      }
    });
  } catch(Exception e){
           System.out.println("Sorry some error occured "+e);
        }
 }
 private void makeGUI()
 {
   setLayout(new FlowLayout());
   l1=new JLabel("Off");
   jb=new JToggleButton("On/Off");
   jb.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent ae){  
      if(jb.isSelected())
            l1.setText("On");
      else
            l1.setText("Off");       
    }
   });
   add(jb);
   add(l1);
 }
}

Output:

No comments:
Write comments