Professional Documents
Culture Documents
GUI Form Exercise: Submit Clear
GUI Form Exercise: Submit Clear
Create the following GIU using the Java language, and make sure the program works as intended:
When Submit button is clicked, the name, the surname and the year the user was born are
displayed in a JOptionPane.showMessage Dialog.
Enter Name:
Enter Surname:
Enter Age:
Submit Clear
ANSWER OF THE QUESTION:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
GUIForm(String title){
setTitle(title);
setSize(500,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(nameInfo);
add(nameText);
add(surnameInfo);
add(surnameText);
add(ageInfo);
add(ageText);
add(btnSubmit);
add(btnClear);
btnSubmit.addActionListener(this);
btnClear.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSubmit){
String name,surname,ageStr ;
String output="";
int age = 0,yearBorn =0;
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
name = nameText.getText().toString();
surname = surnameText.getText().toString();
ageStr = ageText.getText().toString();
try {
age = Integer.parseInt(ageStr);
yearBorn = currentYear - age;
output = "\n Hello " + name + " " + surname +" \n it seems
like you were born in " + yearBorn;
JOptionPane.showMessageDialog(this, output);
JOptionPane.showMessageDialog(this,
"Please enter a number to the age field","Error",
JOptionPane.ERROR_MESSAGE);
System.out.println(ex.getMessage());
}
}
else if (e.getSource() == btnClear){