I want to use the DateChooser in my application. I have already installed and implemented everything in my code and there are no compilation errors, but when I try to run the code the console shows an error that, "Date Must not be Null". What am I doing wrong? Do I have to implement a "base" date first?
kalender = new JPanel();
kalender.setBackground(new Color(135, 206, 235));
kalender.setBounds(0, 0, 506, 250);
LayeredPane.add(kalender);
kalender.setLayout(null);
Termin = new Termin();
SimpleDateFormat sdl = new SimpleDateFormat("dd-MM-yyyy");
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(169, 119, 70, 20);
Termin.setDate(sdl.format(dateChooser.getDate())); // the erro must be here because with out this
kalender.add(dateChooser); //line everything works
System.out.println(Termin);
JButton btnNext3 = new JButton("Next");
btnNext3.setBounds(215, 200, 70, 20);
kalender.add(btnNext3);
btnNext3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LayeredPane.moveToFront(kontakt);
kalender.removeAll();
}
});
So I have a separate Class "Termin" to define all the attributes of an appointment, and I want to set the attributes date to whatever the user chooses in the Date Chooser.
I have tried to set the date in the attribute by hard coding it, but then it would not change when the user makes a selection with the date chooser.
In this line:
Termin.setDate(sdl.format(dateChooser.getDate()));
dateChooser.getDate() returns null because because no date has yet been selected. You need to detect when user has changed the date. You should use code as in this SO: Is it possible to detect a date change on a JCalendar JDateChooser field?
It should look something like:
dateChooser.getDateEditor().addPropertyChangeListener(
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
if ("date".equals(e.getPropertyName())) {
java.util.Date date = (java.util.Date)e.getNewValue();
Termin.setDate(sdl.format(date));
}
}
}
);