开发者

Date Selection in Java

What is the best way for a user to select a future d开发者_开发知识库ate in Java swing? Are there any good freely available libraries that I can do this with?


SwingX library has a lot of good components including excellent date picker

Date Selection in Java


Just for reference, here's a screenshot of the JCalendarDemo from JCalendar, also used in this related project.

Date Selection in Java


I wrote this code back in 2004 in college.. it's all in Java Swing.. feel free to gut it out. I wrote some dispatching software for my university to pay off a $2500 bill. :-)

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 {

........... continued to the NEW FILE DIALOG ..........

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);
        }
    }

Date Selection in Java

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜