How to stop a timer - java

I have the following action performed method
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer();
Object source = e.getSource();
String stringfromDate = tffromDate.getText();
String stringtoDate = tftoDate.getText();
if (source == button) {
// auto refresh begins
int delay = 0; // 0 seconds startup delay
int period = 7000; // x seconds between refreshes
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
// i still have to truly understand what overide does however
// netbeans prompted me to put this
public void run() {
try {
getdata(stringfromDate, stringtoDate);// run get data
// method
} catch (IOException | BadLocationException ex) {
Logger.getLogger(JavaApplication63.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}, delay, period);
}
if (source == button1) {
timer.cancel();
textarea.setText("");
}
}
I have 2 buttons on my GUI one called get information(button) and another called clear information (button1).
I cant seem to get my clear information(button1) to stop the timer and clear the text area so that a new search can be performed. I just cant seem to get this to stop help appreciated.

Consider these changes to your code. Mainly the code does these things differently:
Pull up the declaration of your timer into the class, so that the same timer started before can be cancelled later.
only create a new timer if the start-button was pressed.
//Pulled up for access to make canceable .
protected Timer timer;
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String stringfromDate = tffromDate.getText();
String stringtoDate = tftoDate.getText();
if (source == button) {
//Stop existing one before creating new.
if(timer != null) {
timer.cancel();
}
//Now make new
timer = new Timer();
// auto refresh begins
int delay = 0; // 0 seconds startup delay
int period = 7000; // x seconds between refreshes
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
getdata(stringfromDate, stringtoDate);// run get data
// method
} catch (IOException | BadLocationException ex) {
Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex);
}
}
}, delay, period);
}
if (source == button1) {
//NULLCHECK
if(timer != null) {
timer.cancel();
}
textarea.setText("");
}
}

Related

Java swing countdown timer not working properly

I would like to make a program that shuts down the computer after specific time, but I have troubles making the timer countdown. It must decrement the time in the spinners from which it takes it. I tried to make a dynamic dialog application but it doesn't work.
I apply the whole code if that is not enough.
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//decrements the amount of seconds and the time in the spinners
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
hours.setValue((Integer)m_hours);
minutes.setValue((Integer)m_mins);
seconds.setValue((Integer)m_secs);
label_2.setText(ShutDownDialog.
this.AmountOfTime.toString());
}
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop"); //just to check what happens
}
}
});
StartCountdown.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
hours.setEnabled(false);
minutes.setEnabled(false);
seconds.setEnabled(false);
StartCountdown.setEnabled(false);
StopCount.setEnabled(true);
//calculates the amount of seconds and starts the timer
m_hours = ((Integer)hours.getValue()*3600); //get the hours
m_mins = ((Integer)minutes.getValue()*60); //get the minutes
m_secs = (Integer)seconds.getValue(); //get seconds
AmountOfTime = m_hours + m_mins + m_secs;
timer.start();
//JOptionPane.showMessageDialog(null, AmountOfTime);
}
});
You are updating the values only, if m_secs < 0.
Move
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
outside of the if-block and it will update the labels.
It should now look like this:
private void initialize() {
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
}
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
label_2.setText(ShutDownDialog.this.AmountOfTime.toString());
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop");
}
}
});

Do Java Swing action on specified Date

I'm trying to create a program which has two options:
- Do specific task after countdown (in minutes).
- Do specific task on the date selected.
Both are using jSpinners however, I don't know how to do the action on the specific date, here's the code below, thank you in advance!
protected Object doInBackground() throws Exception {
Timer t = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Checking state of CheckBoxes (one cancels the other)
if(jCheckBox2.isSelected()) {
try {
int delay =(int) jSpinner2.getValue();
jCheckBox1.setSelected(false);
Thread.sleep(delay*60000); //To delay the code from miliseconds to minutes
} catch (InterruptedException ex) {
Logger.getLogger(App_Gui.class.getName()).log(Level.SEVERE, null,
ex);
}
}
else if (jCheckBox1.isSelected()) {
Date delay2 = (Date) jSpinner1.getValue();
jCheckBox2.setSelected(false);
Thread.sleep(delay2); //What should I put here instead of Thread.sleep()???????
}
//If all is right, start the timer
t.start();
t.setRepeats(false);
//Popup dialog
JDialog dialog = new JDialog();
dialog.setLocation(700, 300);
dialog.setSize(600, 400);
dialog.setVisible(true);
//Speed of color changing
try {
Thread.sleep(jSlider1.getValue());
} catch (InterruptedException ex) {
Logger.getLogger(App_Gui.class.getName()).log(Level.SEVERE, null,
ex);
} //Setting the color
dialog.getContentPane().setBackground(jLabel2.getBackground());
dialog.setModal(true);
Assignment_Tajmer_Aplikacija.f.setVisible(false);
return null;
}
protected void done() {
System.out.println("Done!");
}
};
sw.execute();
}
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling cosadde here:
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
//System.out.println(source.getValue());
}
});
}
You have 2 choices:
You compute time difference in milliseconds between current date and target date. So you can start the swing timer. Something like myDate.getTime() - Sytem.currentTimeMillis() (it's probably not always correct)
You use a Library which do it for you (for example Quartz). In this case you need to synchronize your job with the Swing thread using the method SwingUtilities.invokeLater(Runnable).
And never use Thread.sleep() in a Swing application. Start a timer instead.

How to implement timer to make text visible for a certain time and then replace it with another text in Java?

I am creating a mobile phone keypad. I used an array to create buttons.
For one of my buttons, I want "Dialling..." to appear on the JTextField for about 2 seconds on the click and then replace it with "No Signal" for about 2 more seconds and then clear the JTextField.
All this should be done by just 1 click. I know it is to do with timers but I can't seem to implement it.
I have something like this at the moment but it doesn't seem to be working.
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand() == "Dial")
{
timer.start();
counter++;
if(counter ==1)
{
text1.setText("Dialling . . .");
counter = 0;
}
if(e.getsource() == timer)
{
text1.setText("No Signal");
timer.stop();
}
}
Try this
public void actionPerformed(ActionEvent e) {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "Dial")
{
text1.setText("Dialling . . .");
}
}
};
Timer timer = new Timer(1000, taskPerformer); // delay one sec
timer.setRepeats(false);
timer.start();
text1.setText("No Signal");
}

using Thread multiple times for updating UI

I write some timer. and I want to display it in textview after start button is clicked.
What I did.
Every time I
timer = new Thread(new Runnable() {
#Override
public void run() {
while (!stopedButton ) {
time = "";
if (timerMinutes >= 60) {
timerMinutes = 0;
timerHours++;
}
if (timerHours < 10)
time = "0" + String.valueOf(timerHours) + ":";
else
time = String.valueOf(timerHours) + ":";
if (timerMinutes < 10)
time += "0" + String.valueOf(timerMinutes);
else
time += String.valueOf(timerMinutes);
runOnUiThread(new Runnable() {
public void run() {
if (!stopedButton) {
mTimeFromStartValue.setText(time);
timerMinutes++;
} else {
timerMinutes = 0;
timerHours = 0;
}
}
});
Log.e(TAG, ""+timerHours);
Log.e(TAG, ""+timerMinutes);
Log.e(TAG, time);
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
so it works fine, but every time after stop and then start and after doing it many times my timer starts working fast. I try to avoid that kind of situation and I thought that i don't need to create new timer every time. But I need to have working timer after stop start too.
I wrote some code like this:
if(timer.isAlive()){
timer.resume();
}else{
timer.start();
}
But I have got this exception: java.lang.IllegalThreadStateException: Thread already started
so how to solve this ?
You need to create new Thread instance to start new thread. Also You need do use interrupt() method of Thread class.
Use this code to finish Your thread:
#Override
public void run() {
while (true) {
// Your code here
if(isInterrupted ()){
return;
}
}
}
Use this code when stop button was clicked:
timer.interrupt();
timer.join();

Repeated down arrow key pressed in Jtable

On JTable, when down arrow key is pressed repeatedly, multiple KeyEvents are fired in quick succession. My requirement is that I need to act only on last KeyEvent. I am trying to use TimerTask in KeySelectionListener, but it is giving inconclusive results.
Any idea what changes can be done in KeyListener ?
Sample code -
addKeyListener(new KeyListener() {
Timer t = new Timer();
TimerTask tt;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
tt.cancel();
tt = null;
}
#Override
public void keyPressed(KeyEvent e) {
if (tt != null)
return;
tt = new TimerTask() {
#Override
public void run() {
System.out.println("Selected-- "+getModel().getValueAt(getSelectedRow(), 2));
}
};
// t.scheduleAtFixedRate(tt, 0, 500);
t.schedule(tt, 0, 200);
}
});
Thanks
The idea with a Timer (and I strongly suggest to use the javax.swing.Timer class since you interact with Swing components) should work.
Just set the repeats to false, start the timer when you receive a keystroke if the timer is not running, or restart the timer when the timer is already running. This will cause a slight delay in the handling of the last key (delay = the delay you set on the timer), but avoid that you react on each key stroke
I used Timer only. I maintained reference of KeyEvent in listener and if another KeyEvent is received in pre-defined delay (for testing kept it 1 sec), new event is referneced. Thus when there is no new keyEvent for 1 sec, last referred event is used for further processing. its working for now. Feel free to suggest your opinions.
addKeyListener(new KeyListener() {
KeyEvent eventToProcess;
Timer t = new Timer();
TimerTask tt;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(tt != null){
tt.cancel();
tt = null;
}
}
#Override
public void keyReleased(KeyEvent e) {
eventToProcess = e;
tt = new TimerTask() {
#Override
public void run() {
System.out.println("Selected-- "+getModel().getValueAt(getSelectedRow(), 2)+" Key Event > "+eventToProcess.getKeyChar());
}
};
t.schedule(tt, 1000);
}
});

Categories