Description
This program counts the number of times a user clicks a button. The class BClick implements ActionListener interface which contains the actionPerformed() method. The statement b.addActionListener(this); associates ActionListener to the button b, so that when ever a user clicks a button the actionPerformed() method will be called. The value of click is incremented each time the actionPerformed() method is called. The text.setText("Button Clicked "+click+" times"); statement displays the value stored in the variable click to the text box.
Program
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class BClick extends Frame implements ActionListener,WindowListener
{
int click=0;
TextField text=new TextField(25);
//MenuBar m=new MenuBar();
Button b;
int clicks=0;
public static void main(String s[])
{
BClick b=new BClick("ActionListenerWindow");
b.setSize(350,100);
b.setVisible(true);
}
public BClick(String str)
{
super(str);
setLayout(new FlowLayout());
addWindowListener(this);
b=new Button("Click");
add(b);
add(text);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
click++;
text.setText("Button Clicked "+click+" times");
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e)
{
}
public void windowActivated(WindowEvent e)
{
}
public void windowIconified(WindowEvent e)
{
}
public void windowDeiconified(WindowEvent e)
{
}
public void windowDeactivated(WindowEvent e)
{
}
public void windowClosed(WindowEvent e)
{
}
}
Output
| Java program using ActionListener |
No comments:
Post a Comment