BIT401 ยท 2082 ยท 5 marks
Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT.
Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT. [5]
Advanced Java ProgrammingChapter 3: GUI Programming with AWT and SwingText boxes and text fields
Model Answer: AWT Form with Text Fields and Buttons
Program Code:
import java.awt.*;
import java.awt.event.*;
public class SimpleForm extends Frame {
// Declare components
TextField textField1, textField2;
Button okButton, cancelButton;
// Constructor
public SimpleForm() {
// Set frame properties
setTitle("Simple Form");
setSize(300, 200);
setLayout(new FlowLayout());
// Create and add labels
add(new Label("Field 1:"));
// Create first text field
textField1 = new TextField(20);
add(textField1);
add(new Label("Field 2:"));
// Create second text field
textField2 = new TextField(20);
add(textField2);
// Create OK button
okButton = new Button("OK");
add(okButton);
// Create CANCEL button
cancelButton = new Button("CANCEL");
add(cancelButton);
// Add event listeners
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Field 1: " + textField1.getText());
System.out.println("Field 2: " + textField2.getText());
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Handle window close
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
// Main method
public static void main(String[] args) {
new SimpleForm();
}
}
Key Components Explained:
| Component | Purpose |
|---|---|
| Frame | Container window for the form |
| TextField | Input fields for user data (2 fields) |
| Button | Clickable buttons with captions 'OK' and 'CANCEL' |
| FlowLayout | Arranges components in a row |
| ActionListener | Handles button click events |
Output:
- Form displays with two text input fields
- Two buttons labeled "OK" and "CANCEL"
- OK button prints field values to console
- CANCEL button closes the application
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.