Java Swing 日期

Sheeraz Gul 2023年10月12日
  1. 在 Java 中使用 Swing 显示当前日期
  2. 在 Java 中使用 Swing 创建日期选择器
Java Swing 日期

在 Java 中显示或选择日期可以使用 Swing 包来完成。本教程演示了如何在 Java Swing 中处理日期。

在 Java 中使用 Swing 显示当前日期

我们可以使用 Swing 包在 Java 中显示当前日期。要创建 GUI,我们可以实现 Java Swing 中的任何类。

我们使用 PropertyChangeListener 类在 Java Swing 中显示当前日期。请参见下面的示例。

package delftstack;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Show_Date implements PropertyChangeListener {
  public static void main(String[] args) {
    Show_Date DateShow = new Show_Date();
    createWindow(DateShow);
  }

  private static void createWindow(Show_Date DateShow) {
    JFrame J_Frame = new JFrame("Show Date");
    J_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    createUI(J_Frame, DateShow);
    J_Frame.setSize(300, 200);
    J_Frame.setLocationRelativeTo(null);
    J_Frame.setVisible(true);
  }

  private static void createUI(final JFrame J_Frame, Show_Date DateShow) {
    JPanel J_Panel = new JPanel();
    LayoutManager Layout_Manager = new GridLayout(6, 2);
    J_Panel.setLayout(Layout_Manager);
    J_Panel.setSize(200, 200);
    J_Panel.setBorder(BorderFactory.createTitledBorder("Date Format"));

    DateFormat Date_Format = new SimpleDateFormat("dd MMM YYYY");
    JFormattedTextField Today_Date = new JFormattedTextField(Date_Format);
    Today_Date.setName("Today");
    Today_Date.setColumns(10);
    Today_Date.setEditable(false);
    JLabel Today_Label = new JLabel("Date:");
    Today_Label.setLabelFor(Today_Date);
    Today_Date.setValue(new Date());

    J_Panel.add(Today_Label);
    J_Panel.add(Today_Date);
    JPanel Main_Panel = new JPanel();
    Main_Panel.add(J_Panel);

    J_Frame.getContentPane().add(Main_Panel, BorderLayout.CENTER);
  }

  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    // TODO Auto-generated method stub
  }
}

上面的代码将在一个框架中显示当前日期。见输出:

使用 Swing 显示当前日期

在 Java 中使用 Swing 创建日期选择器

我们可以使用 Java Swing 包创建一个 Date Picker 类,从中我们可以从日历中选择一个日期。日期选择器会弹出一个日历,我们可以从中选择任何日期。

下面的代码演示了如何创建和显示日期选择器并从日期选择器中选择日期。参见示例:

package delftstack;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DatePick {
  int DATE_MONTH = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
  int DATE_YEAR = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
  ;
  JLabel J_Label = new JLabel("", JLabel.CENTER);
  String DATE_DAY = "";
  JDialog J_Dialog;
  JButton[] J_Button = new JButton[49];

  public DatePick(JFrame J_Frame_Parent) {
    J_Dialog = new JDialog();
    J_Dialog.setModal(true);
    String[] Header = {
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    JPanel J_Panel1 = new JPanel(new GridLayout(7, 7));
    J_Panel1.setPreferredSize(new Dimension(700, 120));

    for (int i = 0; i < J_Button.length; i++) {
      final int selection = i;
      J_Button[i] = new JButton();
      J_Button[i].setFocusPainted(false);
      J_Button[i].setBackground(Color.white);
      if (i > 6)
        J_Button[i].addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            DATE_DAY = J_Button[selection].getActionCommand();
            J_Dialog.dispose();
          }
        });
      if (i < 7) {
        J_Button[i].setText(Header[i]);
        J_Button[i].setForeground(Color.red);
      }
      J_Panel1.add(J_Button[i]);
    }
    JPanel J_Panel2 = new JPanel(new GridLayout(1, 3));
    JButton Previous_Button = new JButton("<< Previous");
    Previous_Button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        DATE_MONTH--;
        Display_Date();
      }
    });
    J_Panel2.add(Previous_Button);
    J_Panel2.add(J_Label);
    JButton Next_Button = new JButton("Next >>");
    Next_Button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        DATE_MONTH++;
        Display_Date();
      }
    });
    J_Panel2.add(Next_Button);
    J_Dialog.add(J_Panel1, BorderLayout.CENTER);
    J_Dialog.add(J_Panel2, BorderLayout.SOUTH);
    J_Dialog.pack();
    J_Dialog.setLocationRelativeTo(J_Frame_Parent);
    Display_Date();
    J_Dialog.setVisible(true);
  }

  public void Display_Date() {
    for (int i = 7; i < J_Button.length; i++) J_Button[i].setText("");
    java.text.SimpleDateFormat Simple_Date_Format = new java.text.SimpleDateFormat("MMMM yyyy");
    java.util.Calendar Calendar = java.util.Calendar.getInstance();
    Calendar.set(DATE_YEAR, DATE_MONTH, 1);
    int Day_Of_Week = Calendar.get(java.util.Calendar.DAY_OF_WEEK);
    int Days_In_Month = Calendar.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
    for (int i = 6 + Day_Of_Week, Day = 1; Day <= Days_In_Month; i++, Day++)
      J_Button[i].setText("" + Day);
    J_Label.setText(Simple_Date_Format.format(Calendar.getTime()));
    J_Dialog.setTitle("Date Picker");
  }

  public String Set_Picked_Date() {
    if (DATE_DAY.equals(""))
      return DATE_DAY;
    java.text.SimpleDateFormat Simple_Date_Format = new java.text.SimpleDateFormat("dd-MM-yyyy");
    java.util.Calendar Calendar = java.util.Calendar.getInstance();
    Calendar.set(DATE_YEAR, DATE_MONTH, Integer.parseInt(DATE_DAY));
    return Simple_Date_Format.format(Calendar.getTime());
  }
}

public class Date_Picker {
  public static void main(String[] args) {
    JLabel J_Label = new JLabel("Date Selected:");
    final JTextField J_Text_Field = new JTextField(20);
    JButton J_Button = new JButton("Choose the Date");
    JPanel J_Panel = new JPanel();
    J_Panel.add(J_Label);
    J_Panel.add(J_Text_Field);
    J_Panel.add(J_Button);
    final JFrame J_Frame = new JFrame();
    J_Frame.getContentPane().add(J_Panel);
    J_Frame.pack();
    J_Frame.setVisible(true);
    J_Button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        J_Text_Field.setText(new DatePick(J_Frame).Set_Picked_Date());
      }
    });
  }
}

上面的代码将在 Java 中创建一个日期选择器并显示选定的日期。见输出:

Swing 日期选择器

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Swing