简体   繁体   中英

Java - Date picker is not getting the selected date

In my Swing dashboard, I am making use of a date picker. Instead of printing the selected dates it prints the default dates - yyyy-mm-dd (ie the program continues to execute from top to bottom, without waiting for date selection).

Here is my code

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

}

Here is the Date Picker code that I picked from

Below is the 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());
    }
}   

Output

This should print only after date selection

From Date : 0000-00-00

To Date : 0000-00-00

Please help.

So, after spending sometime smacking my head against your code, your basic problem comes down to using a JFrame when you should have used a modal JDialog - See How to Make Dialogs for more details

You kind of had the right idea here...

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

But, you made the dialog visible BEFORE you wired the ActionListener s to the buttons, meaning that when the dialog was made visible, the code execution halted at that point and would wait until the dialog was closed again before continuing on (and adding the ActionListener s)

Don't rely on static , if used incorrectly or excessively, it's a clear sign of a bad design. This is not a means of cross object communication.

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

While this works, I would encourage you to change the setCaadDateInfo method to either return an array or some other object which contains the date information.

Maintaining date values as String is also a bad idea, Java has the java.util.Date or, preferably, java.time.LocalDate classes, you should use them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM