当我更正使用某些功能而不是其他功能时,我发布了这个。我尝试使用JSpinner选择日期和时间然后将其放入计时器中,触发器必须是我选择的日期和时间。
如何通过移动箭头并将日期和时间放入计时器来使用它来改变时间?
import java.awt.BorderLayout;
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.Calendar;
import java.util.Date;
import javax.swing.Timer;
public class SpinnerDateSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSpinner Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerModel model1 = new SpinnerDateModel();
JSpinner spinner1 = new JSpinner(model1);
spinner1.addChangeListener(new CalendarListener());
JLabel label1 = new JLabel("Dates/Date");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.CENTER);
frame.setSize(200, 90);
frame.setVisible(true);
}
}
private class CalendarListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSpinner jSpinner = (JSpinner) e.getSource();
Date date = (Date) jSpinner.getValue();
long delay = date.getTime() - System.currentTimeMillis();
timerStart();
if (delay > 0) {
timer.setInitialDelay((int) delay);
timer.restart();
}
}
}
TimerStart() {
this.timer = new Timer(Integer.MAX_VALUE, (ActionEvent evt) -> {
System.out.println("okey");
});}
答案 0 :(得分:1)
TimerTask
是遗留类,您可以使用ScheduledExecutorService
按计划的时间间隔执行任务,这是最佳做法,如下所示:
Selection6Runable class:
public class Selection6Runable implements Runnable {
public void run() {
//Add code for Selection6 Logic,
// this code will be run everytime when the scheduler runs
}
}
使用以上代码:
ScheduledExecutorService scheduledService= Executors.newScheduledThreadPool(1);
//Change the below time interval according
//to the data received i.e., CalDcB.getSelectedItem()
scheduledService.scheduleAtFixedRate(()-> new Selection6Runable(),
0, 1000L, TimeUnit.MILLISECONDS);
您可以查看here了解更多详情