Java中的日期选择

Posted

技术标签:

【中文标题】Java中的日期选择【英文标题】:Date Selection in Java 【发布时间】:2011-10-08 23:52:27 【问题描述】:

用户在 Java swing 中选择未来日期的最佳方式是什么?有没有什么好的免费库可供我使用?

【问题讨论】:

我的方法可能不是最好的方法,因为它也显示过去的日期,但可以调整。祝你好运! 【参考方案1】:

SwingX 库有很多不错的组件,包括优秀的日期选择器

【讨论】:

没关系,我在http://java.net/downloads/swingx/找到了下载 这是由于 java.net 站点上的迁移。试试这个java.net/downloads/swingx/releases 谢谢。 JXDatePicker 类完全按照我的需要工作。【参考方案2】:

仅供参考,这里是来自JCalendarJCalendarDemo的截图,也用于这个相关的project。

【讨论】:

这是我最喜欢的作品,据我所知,简单、清晰......放在这里 Substance LaF 而不是 JGoodies +1【参考方案3】:

我在 2004 年在大学时编写了这段代码。它全部在 Java Swing 中。随时可以把它删掉。我为我的大学编写了一些调度软件来支付 2500 美元的账单。 :-)

import java.io.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.Timer;
import sun.audio.*;

/**
 * This class contains the graphic user interface for the WantaRide application
 */
public class WantaRide extends JFrame implements ActionListener 

............继续新文件对话框............

class NewFileDialog extends JDialog implements ItemListener, ActionListener 

    /* These are dropdown for the start date */
    private JComboBox startYear, startMonth, startDay;
    /* These are the dropdowns for the end date */
    private JComboBox endYear, endMonth, endDay;
    /* These are all explicit text fields */
    private JTextField usernameText, sourceFileText, newFileText;
    /* These are the actual File objects for the source (Excel file) and new (WantaRide file) */
    private File sourceFile = null, newFile = null;
    /* This is the label for the source file */
    private JLabel sourceFileLabel;
    /* These are password fields for the administrator login and password */
    private JPasswordField passwordText, confirmText;
    /* This is the button to get a file chooser to select the Excel source file */
    private JButton sourceFileButton;
    /* This is the start date used for the date dropdowns */
    private Calendar startDate = Calendar.getInstance();
    /* This is the end date used for the date dropdowns */
    private Calendar endDate = Calendar.getInstance();

    /**
     * This method sets up the New File Dialog window
     */
    public NewFileDialog() 

        super(WantaRide.this, "New WantaRide File", true);

        JPanel datesPanel = new JPanel();
        datesPanel.setBorder(BorderFactory.createTitledBorder
            ("Dates of New Semester"));
        JPanel datesInnerPanel = new JPanel(new GridLayout(2, 4, 10, 10));
        JLabel startDateLabel = new JLabel("Start Date:  ", SwingConstants.RIGHT);
        startYear = new JComboBox();
        buildYearsList(startYear);
        startYear.setSelectedIndex(5);
        startMonth = new JComboBox();
        buildMonthsList(startMonth);
        startMonth.setSelectedIndex(startDate.get(Calendar.MONTH));
        startDay = new JComboBox();
        buildDaysList(startDate, startDay, startMonth);
        startDay.setSelectedItem(Integer.toString(startDate.get(Calendar.DATE)));
        startYear.addItemListener(this);
        startMonth.addItemListener(this);
        startDay.addItemListener(this);
        datesInnerPanel.add(startDateLabel);
        datesInnerPanel.add(startMonth);
        datesInnerPanel.add(startDay);
        datesInnerPanel.add(startYear);
        JLabel endDateLabel = new JLabel("End Date:  ", SwingConstants.RIGHT);
        endYear = new JComboBox();
        buildYearsList(endYear);
        endYear.setSelectedIndex(5);
        endMonth = new JComboBox();
        buildMonthsList(endMonth);
        endMonth.setSelectedIndex(endDate.get(Calendar.MONTH));
        endDay = new JComboBox();
        buildDaysList(endDate, endDay, endMonth);
        endDay.setSelectedItem(Integer.toString(endDate.get(Calendar.DATE)));
        endYear.addItemListener(this);
        endMonth.addItemListener(this);
        endDay.addItemListener(this);
        datesInnerPanel.add(endDateLabel);
        datesInnerPanel.add(endMonth);
        datesInnerPanel.add(endDay);
        datesInnerPanel.add(endYear);
        datesPanel.add(datesInnerPanel, BorderLayout.CENTER);

        JPanel adminPanel = new JPanel();
        adminPanel.setBorder(BorderFactory.createTitledBorder
            ("Administrator Access"));
        JPanel adminInnerPanel = new JPanel();
        JLabel usernameLabel = new JLabel("Username:  ", SwingConstants.RIGHT);
        JLabel passwordLabel = new JLabel("Password:  ", SwingConstants.RIGHT);
        JLabel confirmLabel = new JLabel("Confirm Password:  ", SwingConstants.RIGHT);
        usernameText = new JTextField("Administrator", 15);
        usernameText.setEnabled(false);
        passwordText = new JPasswordField("", 15);
        confirmText = new JPasswordField("", 15);
        adminInnerPanel.setLayout(new GridLayout(3, 2));
        adminInnerPanel.add(usernameLabel);
        adminInnerPanel.add(usernameText);
        adminInnerPanel.add(passwordLabel);
        adminInnerPanel.add(passwordText);
        adminInnerPanel.add(confirmLabel);
        adminInnerPanel.add(confirmText);
        adminPanel.add(adminInnerPanel, BorderLayout.CENTER);

        JPanel topPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        topPanel.add(datesPanel);
        topPanel.add(adminPanel);

        JPanel filePanel = new JPanel(new GridLayout(2, 1, 0, 0));
        filePanel.setBorder(BorderFactory.createTitledBorder
            ("Associated Files"));
        JPanel sourceFilePanel = new JPanel();
        sourceFileLabel = new JLabel("Source File:  ", SwingConstants.RIGHT);
        JPanel sourceButtonPanel = new JPanel();
        sourceFileButton = new JButton("Browse...");
        sourceFileButton.setActionCommand("SourceFileButton");
        sourceFileButton.addActionListener(this);
        sourceButtonPanel.add(sourceFileButton, BorderLayout.CENTER);
        sourceFileText = new JTextField("", 80);
        sourceFileText.setEditable(false);
        sourceFilePanel.add(sourceFileLabel);
        sourceFilePanel.add(sourceButtonPanel);
        sourceFilePanel.add(sourceFileText);
        JPanel newFilePanel = new JPanel();
        JLabel newFileLabel = new JLabel("New File:  ", SwingConstants.RIGHT);
        JPanel newButtonPanel = new JPanel();
        JButton newFileButton = new JButton("Browse...");
        newFileButton.setActionCommand("NewFileButton");
        newFileButton.addActionListener(this);
        newButtonPanel.add(newFileButton, BorderLayout.CENTER);
        newFileText = new JTextField("", 80);
        newFileText.setEditable(false);
        Dimension dim2 = new Dimension(7, 7);
        newFilePanel.add(new Box.Filler(dim2, dim2, dim2));
        newFilePanel.add(newFileLabel);
        newFilePanel.add(newButtonPanel);
        newFilePanel.add(newFileText);
        filePanel.add(sourceFilePanel);
        filePanel.add(newFilePanel);

        JPanel buttonPanel = new JPanel();
        JPanel twoButtonsPanel = new JPanel();
        JButton okButton = new JButton("Create WantaRide File");
        okButton.setActionCommand("OK");
        okButton.addActionListener(this);
        JLabel adviceLabel = new JLabel("  This button may stay depressed for a few seconds. Please be patient.");
        twoButtonsPanel.add(adviceLabel);
        twoButtonsPanel.add(okButton);
        buttonPanel.add(twoButtonsPanel);

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add("Center", filePanel);
        bottomPanel.add("South", buttonPanel);

        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add("Center", topPanel);
        centerPanel.add("South", bottomPanel);

        getContentPane().setLayout(new BorderLayout());
        Dimension dim = new Dimension(10, 10);
        getContentPane().add("North", new Box.Filler(dim, dim, dim));
        getContentPane().add("West", new Box.Filler(dim, dim, dim));
        getContentPane().add("Center", centerPanel);
        getContentPane().add("East", new Box.Filler(dim, dim, dim));
        getContentPane().add("South", new Box.Filler(dim, dim, dim));

        pack();

        double parentWidth = WantaRide.this.getSize().getWidth();
        double parentHeight = WantaRide.this.getSize().getHeight();
        double dialogWidth = this.getSize().getWidth();
        double dialogHeight = this.getSize().getHeight();

        setLocation((int)(parentWidth / 2 - dialogWidth / 2),
            (int)(parentHeight / 2 - dialogHeight / 2));

        setResizable(false);
        setVisible(true);
    

    /**
     * This method builds the list of years for the start
     * date and end date of the semester
     * @param yearsList The combo box containing the years
     */
    private void buildYearsList(JComboBox yearsList) 

        int currentYear = startDate.get(Calendar.YEAR);

        for (int yearCount = currentYear - 5; yearCount <= currentYear + 5; yearCount++)
            yearsList.addItem(Integer.toString(yearCount));
    

    /**
     * This method builds the list of months for the start
     * date and end date of the semester
     * @param monthsList The combo box containing the months
     */
    private void buildMonthsList(JComboBox monthsList) 

        monthsList.removeAllItems();
        for (int monthCount = 0; monthCount < 12; monthCount++)
            monthsList.addItem(Const.MONTHS[monthCount]);
    

    /**
     * This method builds the list of years for the start
     * date and end date of the semester
     * @param dateIn The current date, which will be used for
     * the initial date of the lists
     * @param daysList The combo box that will contain the days
     * @param monthsList The combo box that will contain the months
     */
    private void buildDaysList(Calendar dateIn, JComboBox daysList, JComboBox monthsList) 

        daysList.removeAllItems();
        dateIn.set(Calendar.MONTH, monthsList.getSelectedIndex());
        int lastDay = startDate.getActualMaximum(Calendar.DAY_OF_MONTH);

        for (int dayCount = 1; dayCount <= lastDay; dayCount++)
            daysList.addItem(Integer.toString(dayCount));
    

    /**
     * This method is called when a dropdown selection
     * changes
     * @param event This occurs when a dropdown changes values
     */
    public void itemStateChanged(ItemEvent event) 

        if (event.getSource() == startYear &&
            event.getStateChange() == ItemEvent.SELECTED) 

            int year = Integer.parseInt((String)startYear.getSelectedItem());
            startDate.set(Calendar.YEAR, year);
            startMonth.setSelectedIndex(0);
            startDate.set(Calendar.MONTH, 0);
            buildDaysList(startDate, startDay, startMonth);
            startDate.set(Calendar.DATE, 1);
        
        else if (event.getSource() == startMonth &&
            event.getStateChange() == ItemEvent.SELECTED) 

            startDate.set(Calendar.MONTH, startMonth.getSelectedIndex());
            buildDaysList(startDate, startDay, startMonth);
            startDate.set(Calendar.DATE, 1);
        
        else if (event.getSource() == startDay &&
            event.getStateChange() == ItemEvent.SELECTED) 

            int day = Integer.parseInt((String)startDay.getSelectedItem());
            startDate.set(Calendar.DATE, day);
        
        else if (event.getSource() == endYear &&
            event.getStateChange() == ItemEvent.SELECTED) 

            int year = Integer.parseInt((String)endYear.getSelectedItem());
            endDate.set(Calendar.YEAR, year);
            endMonth.setSelectedIndex(0);
            endDate.set(Calendar.MONTH, 0);
            buildDaysList(endDate, endDay, endMonth);
            endDate.set(Calendar.DATE, 1);
        
        else if (event.getSource() == endMonth &&
            event.getStateChange() == ItemEvent.SELECTED) 

            endDate.set(Calendar.MONTH, endMonth.getSelectedIndex());
            buildDaysList(endDate, endDay, endMonth);
            endDate.set(Calendar.DATE, 1);
        
        else if (event.getSource() == endDay &&
            event.getStateChange() == ItemEvent.SELECTED) 

            int day = Integer.parseInt((String)endDay.getSelectedItem());
            endDate.set(Calendar.DATE, day);
        
    

【讨论】:

@mKorbel,所以当您最初发布代码时,“*”字符会丢失吗?为什么我的代码可以换行而你的没有?仅仅是因为那些星号吗? 我让它变成你的原始版本:-)

以上是关于Java中的日期选择的主要内容,如果未能解决你的问题,请参考以下文章

如何把Excel中的8位的日期字符串转换为日期

使用java在sqlite中选择两个日期之间的行

java+selenium+new——在日期选择器上进行日期选择

Android中的日期选择器日期选择[重复]

角度材料日期选择器中的日期不正确

无法在 detox 中的 android 日期选择器中选择 month_view 中的日期