Trigger event when clicking day in JCalendar?

2

How do I put an event on each day of JCalendar? My intention is to click on a day and create a sort of reminder that is related to the day, in a way that when the user clicks again on the day he sees the reminder, but I have no idea how to make each calendar day work like a button.

    
asked by anonymous 01.12.2015 / 20:37

1 answer

1

As this answer in SOEn , this is possible by adding a listener of type PropertyChangeListener to JCalendar. To do this, you need to retrieve the component responsible for listing the days of the month through your getDayChooser() method, and add the listener to it. So, every time it is clicked on someday, this listener will be triggered.

Here is an example of how to implement:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.SimpleDateFormat;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import com.toedter.calendar.JCalendar;

public class JDateChooserActionDayTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private JCalendar cal;
    private JPanel contentpane;

    public JDateChooserActionDayTest() {
        contentpane = new JPanel(new BorderLayout());

        JLabel label = new JLabel("");
        label.setPreferredSize(new Dimension(contentpane.getWidth(), 20));
        label.setAlignmentX(CENTER_ALIGNMENT);
        label.setHorizontalAlignment(SwingConstants.CENTER);;
        contentpane.add(label, BorderLayout.SOUTH);

        cal = new JCalendar();
        cal.getDayChooser().addPropertyChangeListener("day", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent e) {
                label.setText("Clicou na data: "+ new SimpleDateFormat("dd/MM/yyyy").format(cal.getDate()));
            }
        });

        contentpane.add(cal, BorderLayout.CENTER);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setContentPane(contentpane);
        pack();
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            JDateChooserActionDayTest bg = new JDateChooserActionDayTest();
            bg.setLocationRelativeTo(null);
            bg.setVisible(true);
        });
    }
}

Running:

    
25.09.2017 / 15:18