Reputation: 404
As I corrected my use of some features instead of others, I post this. I try to use JSpinner to choose a Date and Time and put it then into a timer and the trigger must be the Date and Time I choosed.
How could I use it to change the time too by moving the arrows and to put the date and time in the timer ?
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");
});}
Upvotes: 0
Views: 116
Reputation: 22422
TimerTask
is a legacy class, rather you can use ScheduledExecutorService
for executing a task at scheduled intervals, which is a best practice as shown below:
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
}
}
Using the above code:
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);
You can look here for more details
Upvotes: 1