在下面的代码中,我得到了一个NullPointerException:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
timer.setInitialDelay((int) delay);
我尝试添加
//timer = new Timer(0, null);
long delay = dates.getTime() - System.currentTimeMillis();
timer = new Timer(0, null);
new TimerStart();
if (delay >= 0) {
timer.setInitialDelay((int) delay);
timer.restart();
}
为了避免异常,它可以工作,但不会触发定时器吗?
使用此示例,它也适用于计时器触发器,但如何在上面的代码中进行更正:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import java.util.Date;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SpinnerTest {
Timer timer;
Date date;
public static void main(String args[]) {
new SpinnerTest().startApp();
}
private void startApp() {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
date = new Date();
SpinnerModel model1 = new SpinnerDateModel(date,null,null,0);
JSpinner spinner1 = new JSpinner(model1);
spinner1.addChangeListener(new CalendarListener());
spinner1.setEditor(new JSpinner.DateEditor(spinner1, "HH:mm dd-MM-yyyy"));
JLabel label1 = new JLabel("Times/Dates");
JPanel panel1 = new JPanel(new BorderLayout());
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.WEST);
frame.setSize(200, 90);
frame.setVisible(true);
}
private class CalendarListener implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
JSpinner jSpinner = (JSpinner) e.getSource();
date = (Date) jSpinner.getValue() ;
long delay = date.getTime() - System.currentTimeMillis();
//System.out.println(delay);
timerStart();
if (delay > 0) {
timer.setInitialDelay((int) delay);
timer.restart();
}
}
}
private void timerStart() {
this.timer = new Timer(Integer.MAX_VALUE, (ActionEvent evt) -> {
System.out.println("okey");
});}
}