Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top