Question

I have a simple Java program with a JCalendar. I need to know if my JCalendar calendario is or not empty, it means if the user selected or not a date. I was thinking about a method like calendario.isEmpty but it doesn't exist. Maybe I can compare calendario with null but it didn't work. I am using com.toedter.calendar.JDateChooser.

Was it helpful?

Solution

If you are using com.toedter.calendar.JDateChooser, the best way is check the returned date invoking the instance method getDate(). If the returned date is null, that means that the user has not selected a date. e.g.:

public class TestCalendar extends JFrame implements ActionListener {

  private JDateChooser dateChooser;

  public TestCalendar() {
    super("Simple");
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    dateChooser = new JDateChooser();
    add(dateChooser);
    JButton button = new JButton("Check");
    button.addActionListener(this);
    add(button);
    setSize(300, 100);
  }

  public void actionPerformed(ActionEvent e) {
    Date date = dateChooser.getDate();
    if (date == null) {
      JOptionPane.showMessageDialog(TestCalendar.this, "Date is required.");
    }
  }

  public static void main(String[] args) {
    new TestCalendar().setVisible(true);
  }

}

OTHER TIPS

you can try this as well

if(jDateChooser1.getDate()==null){
   JOptionPane.showMessageDialog(this, "Date not selected");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top