I'm creating a swing app with two date fields(date picker) and a button, and the case is like this.
- Initially, the button will be disabled
- if the
startDateChooser
date is not null, then this button should be enabled. - if again the
startDateChooser
date is null(i.e. clearing off the data), this button should be disabled.
I'm able to do the button to be disabled by default, can someone please let me know on how can I do this. I'm basically confused on which event to bind this to.
Below is my current code.
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 732, 502);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JDateChooser startDateChooser = new JDateChooser();
startDateChooser.setBounds(49, 150, 209, 52);
frame.getContentPane().add(startDateChooser);
final JDateChooser endDateChooser = new JDateChooser();
endDateChooser.setBounds(339, 150, 209, 53);
frame.getContentPane().add(endDateChooser);
final JButton btnGenerateEmails = new JButton("Generate Emails");
btnGenerateEmails.setEnabled(false);
startDateChooser.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
btnGenerateEmails.setEnabled(true);
}
});
btnGenerateEmails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Hello There!");
}
});
btnGenerateEmails.setBounds(271, 360, 209, 70);
frame.getContentPane().add(btnGenerateEmails);
JList list = new JList();
list.setBounds(271, 116, 87, -31);
frame.getContentPane().add(list);
}
going through the solution available at Is it possible to detect a date change on a JCalendar JDateChooser field?
I've replaced
startDateChooser.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
btnGenerateEmails.setEnabled(true);
}
});
with
startDateChooser.getDateEditor().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
btnGenerateEmails.setEnabled(true);
}
});
and after doing this change, my button is being enabled by default.
Thanks.