Shoot event by clicking on day in Jcalendar?

Asked

Viewed 838 times

2

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

1 answer

1

In accordance with this answer in Soen, this is possible by adding a type Listener PropertyChangeListener to Jcalendar. For this, you need to redeem the component responsible for listing the days of the month, through your method getDayChooser(), and add Listener to it. So, every time it is clicked on some day, that Listener will be fired.

See an example below 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);
        });
    }
}

Working:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.