Bueno, el siguiente código muestra un JFrame con un JTextArea y un JButton. Cuando se hace clic en los botones, el temporizador envía el evento repetidamente (con un segundo retraso entre ellos) al actionListener relacionado con el botón que agrega una línea con la hora actual.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class TimerTest extends JFrame implements ActionListener{
private static final long serialVersionUID = 7416567620110237028L;
JTextArea area;
Timer timer;
int count; // Counts the number of sendings done by the timer
boolean running; // Indicates if the timer is started (true) or stopped (false)
public TimerTest() {
super("Test");
setBounds(30,30,500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
area = new JTextArea();
area.setBounds(0, 0, 500, 400);
add(area);
JButton button = new JButton("Click Me!");
button.addActionListener(this);
button.setBounds(200, 400, 100, 40);
add(button);
// Initialization of the timer. 1 second delay and this class as ActionListener
timer = new Timer(1000, this);
timer.setRepeats(true); // Send events until someone stops it
count = 0; // in the beginning, 0 events sended by timer
running = false;
System.out.println(timer.isRepeats());
setVisible(true); // Shows the frame
}
public void actionPerformed(ActionEvent e) {
if (! running) {
timer.start();
running = true;
}
// Writing the current time and increasing the cont times
area.append(Calendar.getInstance().getTime().toString()+"\n");
count++;
if (count == 10) {
timer.stop();
count = 0;
running = false;
}
}
public static void main(String[] args) {
// Executing the frame with its Timer
new TimerTest();
}
}
Bueno, este código es una muestra de cómo usar objetos javax.swig.Timer. En relación con el caso particular de la pregunta. La instrucción if para detener el temporizador debe cambiar, y, obviamente, las acciones de la acción realizada.El siguiente fragmento es un esqueleto de la solución actionPerformed:
public void actionPerformed(ActionEvent e) {
if (e.getComponent() == myDealerComponent()) {
// I do this if statement because the actionPerformed can treat more components
if (! running) {
timer.start();
runnig = true;
}
// Hit a card if it must be hitted
switch (getJBTable(JB.total, JB.aces > 0)) {
case 0:
JB.hit();
break;
case 1:
break done;
case 2:
JB.hit();
JB.bet *= 2;
break done;
}
if (JB.total >= 21) { // In this case we don't need count the number of times, only check the JB.total 21 reached
timer.stop()
running = false;
}
}
}
mi humilde opinión esto resuelve el problema, ahora @ user920769 hay que pensar en poner el actionListener y las condiciones de partida/parada ...
@kleopatra: Gracias para mostrarme la existencia de esta clase de temporizador, no sé nada al respecto y es increíble, hacer posible un montón de tareas en una aplicación de swing :)
Muchas gracias por el ejemplo, pero me aparece un error en estas líneas: timer = new Timer (1000, this); timer.setRepeats (true); Diciendo que no puede encontrar el constructor o método adecuado, respectivamente. ¿Estaban obsoletos? – Fractaly
¿Importas la clase Timer? Los métodos no están en desuso incluso en la última versión, por lo tanto, parece ser su error. [Aquí el ApiDoc de Java7] (http://download.oracle.com/javase/7/docs/api/javax/swing/Timer.html) – Charliemops