Using JCalendar in a JDialog

巧了我就是萌 提交于 2019-12-20 05:45:23

问题


My program uses JDialogs to open up forms and in the form I want to use JCalendar for the user to select a date and for me to use it for other methods afterwards.

I have downloaded JCalendar library. I read some example codes but still not sure how to do it. I have an idea that in the form you press a button (Select Date) and like a small window opens with that JCalendar and when the date is selected it is displayed in the form as a TextField.

Can someone recommend me some method of doing this with the least trouble?


回答1:


I have an idea that in the form you press a button (Select Date) and like a small window opens with that JCalendar and when the date is selected it is displayed in the form as a TextField.

You may want to try JDateChooser class present in JCalendar library, which allows selecting a date or type it manually. About the second part, you need to provide a PropertyChangeListener to the date chooser in order to listen the "date" property change and update the text field's text accordingly. For instance something like this:

final JTextField textField = new JTextField(15);

JDateChooser chooser = new JDateChooser();
chooser.setLocale(Locale.US);

chooser.addPropertyChangeListener("date", new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        JDateChooser chooser = (JDateChooser)evt.getSource();
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        textField.setText(formatter.format(chooser.getDate()));
    }
});

JPanel content = new JPanel();
content.add(chooser);
content.add(textField);

JDialog dialog = new JDialog ();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.getContentPane().add(content);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);


来源:https://stackoverflow.com/questions/21946016/using-jcalendar-in-a-jdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!