Open all | Close all
|
Java code to implement close functionality into AWT design
With AWT java coding the ability to allow the user to close the window using the X in the top right hand
corner is not implemented as standard. Below is the Java code for creating a class which extends the standard
Frame class and allows you to implement the close functionality. To use this when creating a Class, instead
of extending(extends) the class frame extend the class ZFrameClose (see example below).
|
The Java code to implement window close functionality
//package awt;
import java.awt.*;
import java.awt.event.*;
public class ZFrameClose extends Frame {
public ZFrameClose(String title) {
super(title);
setSize(300, 400);
setLocation(235, 0);
setWindowListener();
}
private void setWindowListener() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
setVisible(false);
dispose();
System.exit(0);
}
});
}
public static void main(String[] args) {
ZFrameClose aDemo = new ZFrameClose("This is the title" +
" to the Frame");
aDemo.setVisible(true);
}
}
|
The Java code to use window close functionality
//package awt;
import java.awt.*;
import java.awt.event.*;
public class ZButton extends ZFrameClose implements ActionListener{
public ZButton(){
super("This is the Frame showing buttons...");
setLayout(new FlowLayout());
for (int idx=0;idx<9;idx++){
Button b = null;
add(b = new Button("Button"+idx));
b.addActionListener(this);
b.setBackground(Color.RED);
b.setForeground(Color.BLACK);
}
}
public void actionPerformed(ActionEvent event){
String cmd= event.getActionCommand();
for (int idx = 0; idx < 99 ; idx++){
String but = "Button"+idx;
if (cmd.equals(but))
System.out.println("Button "+idx+
" pressed.");
}
}
public static void main(String[] args) {
ZButton aDemo = new ZButton();
aDemo.setVisible(true);
}
}
|
|
|