|
| 1 | +import javax.swing.*; |
| 2 | +import java.awt.*; |
| 3 | +import java.awt.event.ActionEvent; |
| 4 | +import java.awt.event.ActionListener; |
| 5 | +import java.time.LocalDate; |
| 6 | +import java.time.Period; |
| 7 | + |
| 8 | +public class AgeCalculatorApp { |
| 9 | + public static void main(String[] args) { |
| 10 | + SwingUtilities.invokeLater(() -> { |
| 11 | + createAndShowGUI(); |
| 12 | + }); |
| 13 | + } |
| 14 | + |
| 15 | + private static void createAndShowGUI() { |
| 16 | + JFrame frame = new JFrame("Age Calculator"); |
| 17 | + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
| 18 | + |
| 19 | + JPanel panel = new JPanel(); |
| 20 | + panel.setLayout(new GridLayout(3, 2)); |
| 21 | + |
| 22 | + JLabel birthDateLabel = new JLabel("Enter Birthdate (yyyy-mm-dd): "); |
| 23 | + JTextField birthDateField = new JTextField(); |
| 24 | + JLabel ageLabel = new JLabel("Your Age: "); |
| 25 | + JLabel ageResult = new JLabel(""); |
| 26 | + JLabel remainingDaysLabel = new JLabel("Remaining Days Until Next Birthday: "); |
| 27 | + JLabel remainingDaysResult = new JLabel(""); |
| 28 | + |
| 29 | + JButton calculateButton = new JButton("Calculate"); |
| 30 | + |
| 31 | + calculateButton.addActionListener(new ActionListener() { |
| 32 | + @Override |
| 33 | + public void actionPerformed(ActionEvent e) { |
| 34 | + String birthDateText = birthDateField.getText(); |
| 35 | + LocalDate birthDate = LocalDate.parse(birthDateText); |
| 36 | + LocalDate currentDate = LocalDate.now(); |
| 37 | + |
| 38 | + Period age = Period.between(birthDate, currentDate); |
| 39 | + ageResult.setText(age.getYears() + " years, " + age.getMonths() + " months, " + age.getDays() + " days"); |
| 40 | + |
| 41 | + LocalDate nextBirthday = birthDate.withYear(currentDate.getYear()); |
| 42 | + if (nextBirthday.isBefore(currentDate) || nextBirthday.isEqual(currentDate)) { |
| 43 | + nextBirthday = nextBirthday.plusYears(1); |
| 44 | + } |
| 45 | + |
| 46 | + Period remainingDays = Period.between(currentDate, nextBirthday); |
| 47 | + remainingDaysResult.setText(remainingDays.getDays() + " days"); |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + panel.add(birthDateLabel); |
| 52 | + panel.add(birthDateField); |
| 53 | + panel.add(ageLabel); |
| 54 | + panel.add(ageResult); |
| 55 | + panel.add(remainingDaysLabel); |
| 56 | + panel.add(remainingDaysResult); |
| 57 | + |
| 58 | + frame.getContentPane().add(panel, BorderLayout.CENTER); |
| 59 | + frame.getContentPane().add(calculateButton, BorderLayout.SOUTH); |
| 60 | + |
| 61 | + frame.pack(); |
| 62 | + frame.setVisible(true); |
| 63 | + } |
| 64 | +} |
0 commit comments