February 27, 2013

Event Listener example in java frame


Event Handling Interface in java with Examples


EventListener : A Listener is called when user invoke an event either through a user interface or through code. Listener are supported by java swing. There are container listener, caret listener, key event listener, window listener in java. You can implements multiple listener event to same class in java.


 import java.awt.*;
import java.awt.event.*;

public class Technology extends Frame implements WindowListener,ActionListener {
    TextField text = new TextField(20);
    Button b;
    private int numClicks = 0;

    public static void main(String[] args) {
        Technology myWindow = new Technology ("Duck Dynasty");
        myWindow.setSize(350,100);
        myWindow.setVisible(true);
    }

    public Technology(String title) {

        super(title);
        setLayout(new FlowLayout());
        addWindowListener(this);
        b = new Button("Click me");
        add(b);
        add(text);
        b.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        numClicks++;
        text.setText("Button Clicked " + numClicks + " times");
    }

    public void windowClosing(WindowEvent e) {
        dispose();
        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) {}

}





import java.awt.*;
import java.awt.event.*;

class click extends Frame implements ActionListener
{
Button b,p;

click()
{
this.setLayout(null);
b= new Button("pink");
p= new Button("blue");
b.setBounds(100,299,70,20);
p.setBounds(200,299,70,20);
this.add(p);
this.add(b);
b.addActionListener(this);
p.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==p)
setBackground(Color.pink);
if(ae.getSource()==b)
setBackground(Color.blue);
}

public static void main(String a[])
{
click c=new click();
c.setTitle("adding button");
c.setSize(500,500);
c.setVisible(true);
}

}


End of java code

Java source codes

Facebook comments