Problem with Timer object
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 .
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//The main class
public class Elevator_Simulation extends JFrame{
public JLabel state; // display the state of the elevator
private JLabel id; //your name and group
public ButtonPanel control; //the button control panel
private Elevator elevator; // the elevator area
private final int width = 400;
private final int height = 500;
public Container elevatorPanel;
private int delay ;
//constructor
public Elevator_Simulation() {
// Create GUI
setTitle("Elvator Simulation");
setSize(width,height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); buildPanel();
elevator = new Elevator(this);
elevator.beginOperation();
}
public void buildPanel(){
id = new JLabel("MyName SE6",JLabel.CENTER);
elevatorPanel = getContentPane();
control = new ButtonPanel();
elevatorPanel.setLayout(new BorderLayout());
elevatorPanel.add(control,BorderLayout.WEST);
elevatorPanel.add(id,BorderLayout.NORTH);
}
....
// Main method
public static void main(String[] args) throws InterruptedException{
// Create a frame and display it
new Elevator_Simulation();
}
} //the end of Elevator_Simulation class
// The elevator class draws the elevator area and simulates elevator
movement
class Elevator extends JPanel implements ActionListener {
// parameters ....
private Timer tm ;
private final int delay = 200 ;
final private int speed = 40 ;
private Elevator_Simulation app;
// Paint elevator area
public Elevator(Elevator_Simulation app){
// set the parameters of the elevator
}
public void beginOperation(){
tm = new Timer(delay/speed,this);
tm.start();
}
public void paintComponent(Graphics g) {
// paint the elevator
}
//Handle the timer events
public void actionPerformed(ActionEvent e) {
tm.setDelay(delay/speed);
height = getHeight()/8;
int curFloor = 7-yco/height ;
if (yco % height == 0 && app.control.bp[curFloor])
{
tm.stop();
new Pause();
tm.start();
app.control.restoreButtonState(curFloor);
}
.....
}
// i use this class to pause the elevator
class Pause implements ActionListener
{
Timer tmpTimer ;
int times;
public Pause(){
int delayTime = (delay*50)/speed; tmpTimer = new
Timer(delayTime,this); times = 1;
}
public void actionPerformed(ActionEvent e) {
if (times==2){
tmpTimer.stop();
}
else times++;
}
}
} // end of the elevator class