This program calculates the age. Input is taken from the user through a Graphical User Interface (GUI). We will be using the following components in our program.
-
Frame
TextField
Label
Button
Step 1: Creating a Frame
First thing we do is, create a frame. A frame is nothing but the actual window that you’ll see when the program is executed.
Frame is initialized at line 23:
|
1 |
frame = new Frame("Age Calculator - MyCoding.net"); |
After initializing our frame, we set is size and location on the screen. This is done at line 26:
|
1 |
frame.setBounds(x, y,h, br); //Setting bounds, i.e screen location, height,breadth |
By default, the frame’s visibility is set to false, i.e the frame is not visible. So we have to set its visibility to true. Done at line 24:
|
1 |
frame.setVisible(true); //Setting frame visibility to true. |
Next thing we do is set LayOut for the frame, we have put a FlowLayout in this program.
|
1 |
frame.setLayout(new FlowLayout()); //Setting LayOut |
Step 2: Initialize other components.
After finishing the frame, we initialize Buttons, TextField and Label. This is done from line 13 till 22.
|
1 2 3 4 5 6 7 8 9 10 |
Button b= new Button("Tell me my age!"); //Initializing button Button exit = new Button("Exit"); //Initializing button Button clear = new Button("Clear"); //Initializing button dayL = new Label("Day: "); //Initializing Label dayT = new TextField ("Day"); //Initializing TextField monthL = new Label("Month: "); //Initializing Label monthT = new TextField ("Month"); //Initializing TextField yearL = new Label("Year: "); //Initializing Label yearT = new TextField("Year"); //Initializing TextField age = new TextField(); |
Step 3: Add Components to the frame.
After initializing frame and other components, we add those components to the frame. Syntax for doing this is:
|
1 |
frame.add(component); |
Step 4: Add ActionListeners to the frame.
This is the most important part of the program. ActionListeners tell the program that an event has occurred, for example a button is clicked.
We add ActionListener to all the three buttons, so that our program reacts accordingly when a button is clicked.
After adding ActionListener, we create classes which will handle the events. In this program, we have created Class Clear and Exit to perform the required task.
Step 5: Calculate age and display the result.
Whenever the Submit button is clicked, actionPerformed class stores the user entered data in the equivalent variables.
Note: We have put the code in a try block so that we can catch the exception if user doesn’t input a valid date. (If user enters a String or Invalid month.)
After collecting data from the TextFields, our next task will be to parse them into int so we can do the necessary calculations.
CalculateAge() :
The objective of this function is to calculate age based on users input. We first find out current date,month and year from the system using in-built class Date found in
|
1 |
import java.util.Date; |
That was just a brief summary of the program. If you have any questions, feel free to ask.
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
//Made at www.mycoding.net import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JOptionPane; public class MyProject implements ActionListener{ static TextField dayT,monthT,yearT,age; //Creating TextFields static Frame frame; //Creating a frame static Label dayL,monthL,yearL; //Creating Label //This will be our constructor to Initialize the frame and adding components to it. public MyProject(int x,int y,int h, int br){ Button b= new Button("Tell me my age!"); //Initializing button Button exit = new Button("Exit"); //Initializing button Button clear = new Button("Clear"); //Initializing button dayL = new Label("Day: "); //Initializing Label dayT = new TextField ("Day"); //Initializing TextField monthL = new Label("Month: "); //Initializing Label monthT = new TextField ("Month"); //Initializing TextField yearL = new Label("Year: "); //Initializing Label yearT = new TextField("Year"); //Initializing TextField age = new TextField(); //Initializing TextField frame = new Frame("Age Calculator - MyCoding.net"); //Initializing our frame and setting the tittle. frame.setVisible(true); //Setting frame visibility to true. frame.setLayout(new FlowLayout()); //Setting LayOut frame.setBounds(x, y,h, br); //Setting bounds, i.e screen location, height,breadth frame.add(dayL); // Adding Label dayL to frame frame.add(dayT); // Adding TextField dayT to frame frame.add(monthL); // Adding Label monthL to frame frame.add(monthT); // Adding TextField monthT to frame frame.add(yearL); //Adding Label yearL to frame frame.add(yearT); // Adding TextField yearT to frame frame.add(age); //Adding TextField age to frame frame.add(b); //Adding button b frame.add(exit); //Adding button exit frame.add(clear); //Adding button clear //Adding ActionListeners to the buttons in the frame. clear.addActionListener(new Clear()); exit.addActionListener(new Exit()); b.addActionListener(this); } //When clear button is clicked, this class will be called. public class Clear implements ActionListener{ public void actionPerformed(ActionEvent ae) { dayT.setText(""); monthT.setText(""); yearT.setText(""); } } //When exit button is clicked, this class will be called. public class Exit implements ActionListener{ public void actionPerformed(ActionEvent e) { frame.dispose(); //Exits frame } } //When calculate button is clicked, this class will be called. public void actionPerformed(ActionEvent e) { try{String a = dayT.getText(); //Gets date entered by user String b = monthT.getText(); //Gets month entered by user String c = yearT.getText(); //Gets year entered by user //Converts all strings to ints. int day = Integer.parseInt(a); int month = Integer.parseInt(b); int year = Integer.parseInt(c); if(day>31 || month > 12 || day == 0 || month==0) { JOptionPane.showMessageDialog(null,"Please Enter a valid date!"); } else{ int answer = CalculateAge(day,month,year); //Calling the function which will calculate age for us. String ans_op = String.valueOf(answer); //Converting answer from int to string. age.setText(ans_op);} }//Setting age textfield to the calculated answer catch(NumberFormatException ae){ JOptionPane.showMessageDialog(null,"Please Enter a valid date!"); //Prints error message if user inputs non-int value } } //Function to calculate age public int CalculateAge(int day,int month,int year){ Date d = new Date(); int current_day = d.getDate();//Gets current date int current_month = d.getMonth()+1; //Gets current month int current_year = d.getYear()+1900; //Gets current year int answer = (current_year - year); //Calculates age if(current_month>month) { answer--; } if(current_month == month && current_day<day) { answer--; } return answer; } public static void main(String args[]){ MyProject ob = new MyProject(250,200,400,400); //Calling our constructor which manages the entire program } } |
Output:

Tested in Eclipse and Command Line.
Vlad
Latest posts by Vlad (see all)
- Code jam “Tic-Tac-Toe-Tomek” solution in java - April 19, 2013
- Code jam “Minimum Scalar product” solution in java - March 18, 2013
- Code jam Store Credit solution in java - March 10, 2013