Wednesday, January 14, 2009

JAVA: Anonymous Listeners

There is no need to define a named class simply to add a listener object to a button. Java has a somewhat obscure syntax for creating an anonymous innner class listener that implements an interface. There is no need to memorize the syntax; just copy and paste it each time. For example,
class myPanel extends JPanel {
. . .
public MyPanel() {
. . . //in the constructor
JButton b1 = new JButton("Hello");
b1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something for button b1
}
}

);

Creates a class

The above example creates a subclass of Object that implements the ActionListener interface. The compiler creates names for anonymous classes. The JDK typically uses the enclosing class name followed by $ followed by a number, eg, you may see a MyPanel$1.class file generated by the compiler.


ActionListener Example Using Anonymous Inner Classes
-------------------------------------------------------------



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

/****
*
* @author Sabah u Din Irfan
* @Description ActionListener Example Using Anonymous Inner Classes
*/
public class ActionListnerDemo extends JFrame{

JLabel lbl ;
JTextField txt1;
JTextField txt2;
JTextField txt3;
JButton btnAdd;
JButton btnSub;

ActionListnerDemo()
{
// Set Frame Window properties
super("Action Listner Demo!!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Get Container
Container container = getContentPane();
container.setLayout(new FlowLayout());
// Create Components
lbl = new JLabel(" Please Enter two values in text fields:");
txt1 = new JTextField(15);
txt2 = new JTextField(15);
txt3 = new JTextField(15);
btnAdd = new JButton("Add");
btnSub = new JButton("Sub");
// Add Components

container.add(lbl);
container.add(txt1);
container.add(txt2);
container.add(txt3);
container.add(btnAdd);
container.add(btnSub);

// Add Action Listners.. Use Annonymous Inner Classes

btnAdd.addActionListener( new ActionListener() {

public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a+b;

txt3.setText(c+"");

}
}
);

////////////////////
btnSub.addActionListener( new ActionListener() {

public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a-b;

txt3.setText(c+"");

}
}
);

// Make frame visible and set its size
setVisible(true);
pack();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ActionListnerDemo frame = new ActionListnerDemo();

}

}

1 comment:

Unknown said...

thnax sir...its very helping