Thursday, 21 May 2015

Filled Under:

How To Use JToogle Button In Java

In our last tutorial  how to create simple toggle button  we illustrate how to create simple jtoggle button in java but in this example we have performing on off operation using item state changed when toggle button is on textfield is active when toggle button become off   textfield become inactivated  until its state changed by user.Following are the different constructors of jtoggle button.

CONSTRUCTORS OF TOOGLE BUTTON:

JToggleButton(String)
JToggleButton(Action)
JToggleButton(String,boolean)
JToggleButton(Icon)
JToggleButton(Icon,boolean)
JToggleButon(String,Icon,boolean)
JToggleButon(String,Icon)

Here string specifies the text that has to be appeared in toggle button we can also use image in jtoggle button by using these constructors here boolean specify that the toggle button is initially selected or not.


CODING:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class myframe extends JFrame implements ItemListener
{

JToggleButton jb;
JTextField t1;
myframe()
{

setTitle("JTOGGLE BUTTON");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t1 = new JTextField(15);
jb = new JToggleButton("ON");
jb.setPreferredSize(new Dimension(150,50));
jb.setBackground(Color.cyan);
add(jb);
add(t1);
jb.addItemListener(this);
setSize(700, 200);
setVisible(true);

public void itemStateChanged(ItemEvent eve)
{   
if(jb.isSelected())
{
    jb.setText("OFF");
t1.setEnabled(false);
}
else
{
    jb.setText("ON");
t1.setEnabled(true);
}
}  
}

public class togg
{

public static void main(String[] args) {

myframe x = new myframe();
}
}

OUTPUT:











0 comments:

Post a Comment