Re: Problem with Timer object
On 21 Wrz, 18:20, tkt...@gmail.com wrote:
Hi bros. I am encountering with a problem about Timer .
I am simulating a elevator using Java GUI . My elevator includes an
rectangular elevator and a ButtonPanel (an array of buttons which
indicate the floors ) . The elevator runs up and down between the
storeys . What i want is when i press a button in the buttonPanel ie
button number 5 , the elevator will stop when it reachs storey 5 for
an amount of time and continue moving after that . I use timer but the
elevator can't stop .Here is the code .please help me . Thanks in
advance .
[...]
} // end of the elevator class
Doing it as Knute Johnson has written in his post is good idea.
To help you with timers, I have written small snippet:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SwingTimerTest {
static class TestPanel extends JPanel implements ActionListener{
private static final int MOVE_DELAY = 2000;
private static final int PAUSE_DELAY = 500;
enum Mode {
MOVE,
PAUSE
}
private Timer timer;
private Mode mode;
public TestPanel() {
super();
JButton runButton = new JButton("Run");
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
runTest();
}
});
add(runButton);
}
@Override
public void actionPerformed(ActionEvent event) {
switch (mode) {
case MOVE:
System.out.println("Pauses...");
mode = Mode.PAUSE;
timer.setInitialDelay(PAUSE_DELAY);
timer.start();
break;
case PAUSE:
System.out.println("Moves...");
mode = Mode.MOVE;
timer.setInitialDelay(MOVE_DELAY);
timer.start();
break;
}
}
private void runTest() {
mode = Mode.MOVE;
timer = new Timer(MOVE_DELAY, this);
timer.setRepeats(false);
timer.start();
}
}
public static void main(String[] args) {
TestPanel panel = new TestPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Przmek