Credits

Sunday, August 29, 2010

Java's Action and Window Listeners

 Java programmers prefer to use Swing components because of their ease and flexibility, however, when AWT components are rather chosen, we can still integrate codes to make sure that we get to perform what we must accomplish.

The program below makes use instead of Frame component from AWT package but when window close button is clicked, no action is rather performed. Thus, a call for window listener must be done.

The thing with event handling is we have to define all the methods of this listener even if it means, these methods may not perform anything. This is the case for ClosingFrame class where a need  to close the frame can be made.
 
[+/-] show/hide


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

//a sample program that uses awt objects. press ctrl c to end.
public class ButtonActionEvent extends Frame implements ActionListener
{
Button redButton = new Button("Red");
Button greenButton = new Button("Green");
Button blueButton = new Button("Blue");

public ButtonActionEvent(){
setLayout(new FlowLayout());
setTitle("Button Action Event Frame");
setSize(300,150);

ClosingFrame close=new ClosingFrame();
//ClosingFrameAdapter close = new ClosingFrameAdapter();
addWindowListener(close);//calls a listner in Closing Frame

redButton.addActionListener(this);
add(redButton);

greenButton.addActionListener(this);
add(greenButton);
blueButton.addActionListener(this);
add(blueButton);
setVisible(true);
}

public void actionPerformed(ActionEvent e){
// Object source = e.getSource();
if (e.getSource()==redButton)
this.setBackground(Color.red);
else if (e.getSource()==greenButton)
setBackground(Color.green);
else setBackground(Color.blue);

}

public static void main (String[] args){
ButtonActionEvent apps = new ButtonActionEvent();

}
}

/*the other file to close the frame*/
import java.awt.*;
import java.awt.event.*;

//a sample program that uses awt objects.
public class ClosingFrame extends Frame implements WindowListener
{


public ClosingFrame(){
addWindowListener(this);

}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowClosed(WindowEvent e)
{
}
public void windowDeiconified(WindowEvent e){

}public void windowIconified(WindowEvent e){

}public void windowOpened(WindowEvent e){

}public void windowActivated(WindowEvent e){

}public void windowDeactivated(WindowEvent e){

}
public static void main (String[] args){
ClosingFrame apps = new ClosingFrame();
apps.setSize(100,60);
apps.setVisible(true);

}


}

AddThis