A Custom JDialog That Displays Current Date and Time - Java Swing

Java examples for Swing:JDialog

Description

A Custom JDialog That Displays Current Date and Time

Demo Code

import java.awt.BorderLayout;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;

class DateTimeDialog extends JDialog {
  JLabel dateTimeLabel = new JLabel("Datetime placeholder");
  JButton okButton = new JButton("OK");

  public DateTimeDialog() {
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    this.setTitle("Current Date and Time");
    this.setModal(true);

    LocalDateTime ldt = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter
        .ofPattern("EEEE MMMM dd, yyyy hh:mm:ss a");
    String dateString = ldt.format(formatter);

    dateTimeLabel.setText(dateString);//w  ww .  ja v a  2  s.co m

    this.add(dateTimeLabel, BorderLayout.NORTH);
    this.add(okButton, BorderLayout.SOUTH);

    okButton.addActionListener(e -> DateTimeDialog.this.dispose());
  }
}

Related Tutorials