Timer doesn't work when another button is pressed (applet) - java

I'm making an applet which has two buttons: step back and step forward.
I have the same timer in every button to execute an animation. If I push step forward it works fine, and the animation runs, but if i push step back, the animation doesn't run or is bad runned (in a wrong position and velocity).
I guess the problem is the timer doesn't stop correctly and is running when start the timer again, but I donĀ“t know how to solve it.
This is the code of the step forward button:
//Code of the button "Paso a Paso"
this.botonPasoAPaso = new JButton("Paso a paso");
this.botonPasoAPaso.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Avoid timer to accelerate
if (timer != null && timer.isRunning()) {
timer.stop();
}
//Code of the timer, makes an animation
timer = new Timer(35, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (pasoAPaso <= listaPaquetes.size()) {
Paquete p = listaPaquetes.get(pasoAPaso);
p.animar();
panelGrafo.removeAll();
panelGrafo.updateUI();
panelGrafo.setPaquete(p);
panelGrafo.setAnimar(true);
panelGrafo.repaint();
}
}
});
timer.start();
pasoAPaso++;
}
});
This is the code of the step back button:
this.botonAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (timer != null && timer.isRunning()) {
timer.stop();
}
timer = new Timer(35, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (pasoAPaso < listaPaquetes.size() && pasoAPaso>=0) {
Paquete p = listaPaquetes.get(pasoAPaso);
p.animar();
panelGrafo.removeAll();
panelGrafo.updateUI();
panelGrafo.setPaquete(p);
panelGrafo.setPasoAPaso(pasoAPaso);
panelGrafo.setAnimar(true);
panelGrafo.repaint();
//Actualizar matriz del render para pintar celdas
RenderTabla.matrizTotal = new Cuadrado[pasos.get(pasoAPaso).length][pasos.get(pasoAPaso)[0].length];
RenderTabla.matrizTotal = pasos.get(pasoAPaso);
tabla.introducirDatos(pasos.get(pasoAPaso),false);
}
}
});
timer.start();
pasoAPaso--;
}
});
This is a video of the applet to see what's happening
If you see the video, when I click the "Paso a Paso" (Step forward) button, a truck is animated, but when I click the "rewind" (Step back) button, it doesn't work (appears a truck but is not correctly animated), and if i click again nothing happens.
Thanks.

Related

JButton Value If Else Conditon with JSpinner doesn't work properly

I'm trying to make a timer that has a jbutton called Short Break and a jbutton called Customize.
By clicking the default Short Break button the time will be set to 5.00 minutes.
But the user can customize the time with the help of JSpinner by clicking on the customize button.
But if the user wants to reduce the short break time by clicking on the customize button, then clicking on the short break button after customizing will show the customized time.
But after customizing, the customized time is shown, but clicking on the short break button without customizing does not show the default value. Means that the if condition only work but the else condition doesn't.
My JSpinner Code:
spinnerShortBreak.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
value2 = Integer.parseInt(String.valueOf(spinnerShortBreak.getValue()));
}
});
The Short Break button Code:
btnShortBreak.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
second = 00;
minute = 05;
if (spinnerShortBreak !=null && spinnerShortBreak.getModel().getValue().equals(value2)) {
lblMinute.setText(String.valueOf(value2));
}
else if(spinnerShortBreak == null && spinnerShortBreak.getValue() == null) {
btnStartStop.setText("Start");
lblMinute.setText("05");
lblSecond.setText("00");
}
}
});
I find a solution. If i check the value is equal to 0 or greater than 0 the code will work perfectly.
here the button code:
btnShortBreak.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
if(value2 > 0){
second = 00;
lblMinute.setText("0"+String.valueOf(value2));
btnStartStop.setText("Start");
lblSecond.setText("00");
}
else if(value2 == 0) {
second = 00;
minute = 05;
btnStartStop.setText("Start");
lblMinute.setText("05");
lblSecond.setText("00");
}
}
});

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");
}
}
});

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");
}

How to stop a swing timer

I am working on a GUI. This is the code (one ActionListener for Button and one for timer). I have a list of images to display one by one. On pressing a stop button, i am supposed to stop the timer and display the current image. On pressing the next button, i am supposed to display the next image.
This is the part of a code on Progressive Image Transmission which means displaying each of the current image in an order of clarity(resolution). This is what handler action Listener does for each image.
Problems:
On Clicking stop, the timer is not stopping, rather stop's action listener is further creating more timers i guess.(Note : Next and Stop share same Action Listeners)
On clicking next, the present running timer needs to be stopped and a fresh timer needs to be started. (Note : I used timer.restart() but it also didnt serve the purpose)
Help would be appreciated.
public void actionPerformed(ActionEvent arg0) {
int threads=0;
System.out.println("Listening : "+arg0.getActionCommand());
if(arg0.getActionCommand().equals("Send")){
stopButton.setEnabled(true);
nextButton.setEnabled(true);
}
else if(arg0.getActionCommand().equals("Stop")){
timer.stop();
saveButton.setEnabled(true);
stopButton.setEnabled(false);
}
else if(arg0.getActionCommand().equals("Next")){
stopButton.setEnabled(true);
saveButton.setEnabled(false);
timer.restart();
}
try {
image = ImageIO.read(new File(pathName[imageNo])).getScaledInstance(512,512 , BufferedImage.SCALE_SMOOTH);
}catch (IOException e) {
e.printStackTrace();
}
senderImage = new ImageIcon(image);
senderImageLabel.setIcon(senderImage);
senderFrame.setVisible(true);
ImageToMatrix(getImage(pathName[imageNo]));
Compress();
k=senderMatrix.length-1;
imageR=Decompress(k);
imageR=imageR.getScaledInstance(512, 512, BufferedImage.SCALE_SMOOTH);
receivedImage = new ImageIcon(imageR);
receiverImageLabel.setIcon(receivedImage);
receiverFrame.getContentPane().add(BorderLayout.EAST,receiverImageLabel);
receiverFrame.setVisible(true);
Handler handler = new Handler();
timer = new Timer(1000,handler);
timer.start();
sendButton.setEnabled(false);
imageNo = (imageNo+1)%5;
}
class Handler implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
System.out.println("image: "+imageNo+" matrix:"+k );
k-=1;
imageR=Decompress(k);
imageR=imageR.getScaledInstance(512, 512, BufferedImage.SCALE_SMOOTH);
receivedImage = new ImageIcon(imageR);
receiverImageLabel.setIcon(receivedImage);
receiverFrame.getContentPane().add(BorderLayout.EAST,receiverImageLabel);
receiverFrame.setVisible(true);
if(k==0){
timer.stop();
}
}
}

Java: Double-Click a JSlider to Reset

I have a JSlider that sets the speed of my metronome, from 40 - 200, where 120 is the default, in the middle.
When the user clicks the metronome button, the metronome plays at the speed displayed on the JSlider - the user drags the slider to the right, the speed of the metronome increases, and it decreases if they slide it to the left.
How do I add functionality so that if the user double-clicks on the JSlider button, it defaults back to 120 - in the middle?
Here is my code:
public Metronome() {
tempoChooser = new JSlider();
metronomeButton = new JToggleButton();
JLabel metText = new JLabel("Metronome:");
add(metText);
...
tempoChooser.setMaximum(200);
tempoChooser.setMinimum(40);
tempoChooser.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tempoChooserStateChanged(evt);
}
});
add(tempoChooser);
...
}
private void tempoChooserStateChanged(javax.swing.event.ChangeEvent evt) {
final int tempo = tempoChooser.getValue();
if (((JSlider) evt.getSource()).getValueIsAdjusting()) {
setMetronomeButtonText(tempo);
} else {
processTempoChange(tempo);
}
}
thanks in advance!
This should help you out: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
You need to read up on that and implement MouseListener. You can use int getClickCount() to count how many times the user has clicked, which will help you read double clicks.
Hope this helps!
Even though I dont see a question, my gues is you are looking for MouseListener.
Not simple job, you have to add javax.swing.Timer and listening if during fixed period Mouse cliked once or twice times, for example
I recently wrote something similar so I could differentiate between single and double left mouse-button clicks:
private Timer timer;
#Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1){
if (timer == null) {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() { // timer expired before another click received, therefore = single click
this.cancel();
timer = null;
/* single-click actions in here */
}
}, (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"));
}
else { // received another click before previous click (timer) expired, therefore = double click
timer.cancel();
timer = null;
/* double-click actions in here */
}
}
}

Categories