Java - 日期选择器没有获得所选日期

时间:2018-02-28 04:50:05

标签: java swing

在我的Swing仪表板中,我正在使用日期选择器。它不打印所选日期,而是打印默认日期 - yyyy-mm-dd(即程序继续从上到下执行,无需等待日期选择)。

这是我的代码

package com.example.test;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Dashboard extends JFrame {

    private static final long serialVersionUID = 9028454994792295975L;
    static String FROM_DATE = "0000-00-00";
    static String TO_DATE = "0000-00-00";   

    Dashboard() {
        setTitle("Dashboard");
        setSize(300, 300); // width, height
        setLocationRelativeTo(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        placeComponents(this);
        setResizable(false);
        setVisible(true);
    }

    private static void placeComponents(JFrame frame) {
        frame.setLayout(null);

        JButton activeDirectoryRefreshButton = new JButton("Refresh");
        activeDirectoryRefreshButton.setActionCommand("Refresh Active Directory");
        activeDirectoryRefreshButton.setBounds(150, 50, 80, 25);
        frame.add(activeDirectoryRefreshButton);

        //Other buttons go here

        activeDirectoryRefreshButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {                
                setCaadDateInfo();
                System.out.println("This should print only after date selection");
                System.out.println("From Date : " + FROM_DATE);
                System.out.println("To Date : " + TO_DATE);
            }
        });
    }   

    public static void setCaadDateInfo() {
        JLabel fromLabel = new JLabel("From Date:", SwingConstants.CENTER);
        final JTextField fromDate = new JTextField(12);
        JButton fromButton = new JButton("Pick Date");

        JLabel toLabel = new JLabel("To Date:", SwingConstants.CENTER);
        final JTextField toDate = new JTextField(12);
        JButton toButton = new JButton("Pick Date");

        JLabel dummyLabel1 = new JLabel("");
        JButton okButton = new JButton("Ok");
        JLabel dummyLabel2 = new JLabel("");

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3,3));

        panel.add(fromLabel);
        panel.add(fromDate);
        panel.add(fromButton);

        panel.add(toLabel);
        panel.add(toDate);
        panel.add(toButton);

        panel.add(dummyLabel1);
        panel.add(okButton);
        panel.add(dummyLabel2);

        final JFrame jframe = new JFrame("AD Date Selector");
        jframe.getContentPane().add(panel);
        jframe.setLocationRelativeTo(jframe);               
        jframe.pack();
        jframe.setVisible(true);

//      final JDialog jdialog = new JDialog(jframe, "AD Date Selector");
//      jdialog.setModal(true);
//      jdialog.getContentPane().add(panel);
//      jdialog.setLocationRelativeTo(null);                
//      jdialog.pack();
//      jdialog.setVisible(true);

        fromButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                FROM_DATE = new DatePickerUtil(jframe).setPickedDate();
                fromDate.setText(FROM_DATE);
            }
        });

        toButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                TO_DATE = new DatePickerUtil(jframe).setPickedDate();
                toDate.setText(TO_DATE);
            }
        });

        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.out.println("Ok button clicked");
                jframe.setVisible(false);               
            }
        });

    }

    public static void main(String[] args) {
        new Dashboard();        
    }

}

以下是我从

中挑选的Date Picker code

以下是代码:

package com.example.test;

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

/*
 * Code taken from : https://www.roseindia.net/tutorial/java/swing/datePicker.html
 */

public class DatePickerUtil {
    int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
    int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);;
    JLabel l = new JLabel("", JLabel.CENTER);
    String day = "";
    JDialog d;
    JButton[] button = new JButton[49];

    public DatePickerUtil(JFrame parent) {
        d = new JDialog();
        d.setModal(true);
        String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
        JPanel p1 = new JPanel(new GridLayout(7, 7));
        p1.setPreferredSize(new Dimension(430, 120));

        for (int x = 0; x < button.length; x++) {
            final int selection = x;
            button[x] = new JButton();
            button[x].setFocusPainted(false);
            button[x].setBackground(Color.white);
            if (x > 6)
                button[x].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        day = button[selection].getActionCommand();
                        d.dispose();
                    }
                });
            if (x < 7) {
                button[x].setText(header[x]);
                button[x].setForeground(Color.red);
            }
            p1.add(button[x]);
        }
        JPanel p2 = new JPanel(new GridLayout(1, 3));
        JButton previous = new JButton("<< Previous");
        previous.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                month--;
                displayDate();
            }
        });
        p2.add(previous);
        p2.add(l);
        JButton next = new JButton("Next >>");
        next.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                month++;
                displayDate();
            }
        });
        p2.add(next);
        d.add(p1, BorderLayout.CENTER);
        d.add(p2, BorderLayout.SOUTH);
        d.pack();
        d.setLocationRelativeTo(parent);
        displayDate();
        d.setVisible(true);
    }

    public void displayDate() {
        for (int x = 7; x < button.length; x++)
            button[x].setText("");
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMMM yyyy");
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.set(year, month, 1);
        int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
        int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
        for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
            button[x].setText("" + day);
        l.setText(sdf.format(cal.getTime()));
        d.setTitle("Date Picker");
    }

    public String setPickedDate() {
        if (day.equals(""))
            return day;
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.set(year, month, Integer.parseInt(day));
        return sdf.format(cal.getTime());
    }
}   

输出

这应该仅在日期选择之后打印

From Date : 0000-00-00

To Date : 0000-00-00

请帮忙。

1 个答案:

答案 0 :(得分:0)

因此,在花了一些时间对付代码后,您的基本问题归结为当您应该使用模式JFrame时使用JDialog - 有关详情,请参阅How to Make Dialogs

你在这里有正确的想法......

final JFrame jframe = new JFrame("AD Date Selector");
jframe.getContentPane().add(panel);
jframe.setLocationRelativeTo(jframe);               
jframe.pack();
jframe.setVisible(true);

//final JDialog jdialog = new JDialog(jframe, "AD Date Selector");
//jdialog.setModal(true);
//jdialog.getContentPane().add(panel);
//jdialog.setLocationRelativeTo(null);                
//jdialog.pack();
//jdialog.setVisible(true);

但是,在将ActionListener连接到按钮之前,您已使对话框可见,这意味着当对话框可见时,代码执行在此时停止,并等到对话框再次关闭之前继续(并添加ActionListener s)

不要依赖static,如果使用不当或过度,则表明设计不良。这不是跨对象通信的手段。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Dashboard dashboard = new Dashboard();
            }
        });
    }

    public class Dashboard extends JFrame {

        private static final long serialVersionUID = 9028454994792295975L;

        JTextField fromDate;
        JTextField toDate;

        Dashboard() {
            setTitle("Dashboard");
            setSize(300, 300); // width, height
            setLocationRelativeTo(null);
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            placeComponents(this);
//            setResizable(false);
            setVisible(true);
        }

        private void placeComponents(JFrame frame) {
            frame.setLayout(null);

            JButton activeDirectoryRefreshButton = new JButton("Refresh");
            activeDirectoryRefreshButton.setActionCommand("Refresh Active Directory");
            activeDirectoryRefreshButton.setBounds(150, 50, 80, 25);
            frame.add(activeDirectoryRefreshButton);

            //Other buttons go here
            activeDirectoryRefreshButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setCaadDateInfo();
                    System.out.println("This should print only after date selection");
                    System.out.println("From Date : " + fromDate.getText());
                    System.out.println("To Date : " + toDate.getText());
                }
            });
        }

        public void setCaadDateInfo() {
            JLabel fromLabel = new JLabel("From Date:", SwingConstants.CENTER);
            fromDate = new JTextField(12);
            JButton fromButton = new JButton("Pick Date");

            JLabel toLabel = new JLabel("To Date:", SwingConstants.CENTER);
            toDate = new JTextField(12);
            JButton toButton = new JButton("Pick Date");

            JLabel dummyLabel1 = new JLabel("");
            JButton okButton = new JButton("Ok");
            JLabel dummyLabel2 = new JLabel("");

            JPanel panel = new JPanel();
            panel.setLayout(new GridLayout(3, 3));

            panel.add(fromLabel);
            panel.add(fromDate);
            panel.add(fromButton);

            panel.add(toLabel);
            panel.add(toDate);
            panel.add(toButton);

            panel.add(dummyLabel1);
            panel.add(okButton);
            panel.add(dummyLabel2);

            final JDialog jframe = new JDialog(this, "AD Date Selector", true);
            fromButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String value = new DatePickerUtil(fromButton).setPickedDate();
                    fromDate.setText(value);
                }
            });

            toButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String value = new DatePickerUtil(toButton).setPickedDate();
                    toDate.setText(value);
                }
            });

            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    System.out.println("Ok button clicked");
                    jframe.setVisible(false);
                }
            });

            jframe.getContentPane().add(panel);
            jframe.setLocationRelativeTo(jframe);
            jframe.pack();
            jframe.setVisible(true);

        }

    }

    public class DatePickerUtil {

        int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
        int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
        JLabel l = new JLabel("", JLabel.CENTER);
        String day = "";
        JDialog d;
        JButton[] button = new JButton[49];

        public DatePickerUtil(Component parent) {
            d = new JDialog(SwingUtilities.windowForComponent(parent));
            d.setModal(true);
            String[] header = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"};
            JPanel p1 = new JPanel(new GridLayout(7, 7));
            p1.setPreferredSize(new Dimension(430, 120));

            for (int x = 0; x < button.length; x++) {
                final int selection = x;
                button[x] = new JButton();
                button[x].setFocusPainted(false);
                button[x].setBackground(Color.white);
                if (x > 6) {
                    button[x].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent ae) {
                            day = button[selection].getActionCommand();
                            d.dispose();
                        }
                    });
                }
                if (x < 7) {
                    button[x].setText(header[x]);
                    button[x].setForeground(Color.red);
                }
                p1.add(button[x]);
            }
            JPanel p2 = new JPanel(new GridLayout(1, 3));
            JButton previous = new JButton("<< Previous");
            previous.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    month--;
                    displayDate();
                }
            });
            p2.add(previous);
            p2.add(l);
            JButton next = new JButton("Next >>");
            next.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    month++;
                    displayDate();
                }
            });
            p2.add(next);
            d.add(p1, BorderLayout.CENTER);
            d.add(p2, BorderLayout.SOUTH);
            d.pack();
            d.setLocationRelativeTo(parent);
            displayDate();
            d.setVisible(true);
        }

        public void displayDate() {
            for (int x = 7; x < button.length; x++) {
                button[x].setText("");
            }
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMMM yyyy");
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.set(year, month, 1);
            int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
            int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
            for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++) {
                button[x].setText("" + day);
            }
            l.setText(sdf.format(cal.getTime()));
            d.setTitle("Date Picker");
        }

        public String setPickedDate() {
            if (day.equals("")) {
                return day;
            }
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.set(year, month, Integer.parseInt(day));
            return sdf.format(cal.getTime());
        }
    }
}

虽然这有效,但我建议您更改setCaadDateInfo方法,以返回包含日期信息的数组或其他对象。

维护日期值为String也是一个坏主意,Java有java.util.Date或者最好是java.time.LocalDate类,你应该使用它们