Hi guys,

i am trying to implement elevator simulation but stuck in some ways.

1st. i would like to set the background of my elevator class area into yellow but when i tried to do so by typing app.setBackground(COLOR.YELLOW) under class Elevator, i unable to change it.

2nd. i tried to simulate the movement of the elevator moving up and down using timer but under paint component i already set the elevator area to be yco = height * 7 which will make the elevator in the 1st floor but then it will makes the timer does not work. but if i delete the yco = height * 7, it will work but it will at the top floor.

the codes:

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


    //constructor
    public Elevator_Simulation() {
        // Create GUI

        //container for all the panels
        Container container = getContentPane();
        //name and group (with a color)
        id = new JLabel("Name : Anthony Salim Kwang", SwingConstants.CENTER);
        id.setForeground(Color.red);
        JPanel id_panel = new JPanel();
        id_panel.add(id);
        container.add(id, BorderLayout.NORTH);

        //all the 8 buttons panel
        control = new ButtonPanel();
        JPanel control_panel = new JPanel();
        control_panel.add(control);
        container.add(control, BorderLayout.WEST);

        //state of elevator (up/down)
        state = new JLabel("elevator up/down", SwingConstants.CENTER);
        JPanel state_panel = new JPanel();
        state_panel.add(state);
        container.add(state, BorderLayout.SOUTH);

    }

    // Main method
    public static void main(String[] args) {
        // Create a frame and display it

        Elevator_Simulation frame = new Elevator_Simulation();
        frame.setTitle("lab1: Elevator Simulation");
        frame.setSize(400, 300);

        //add the elevator area
        frame.getContentPane().add(new Elevator(frame), BorderLayout.CENTER);
        

        //exit upon closing
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //center the frame
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screenSize.width - frame.getWidth()) / 2;
        int y = (screenSize.height - frame.getHeight()) / 2;

        frame.setLocation(x, y);
        frame.setVisible(true);
    }
} //the end of Elevator_Simulation class

//The ButtonPanel class receives and handles button pressing events
class ButtonPanel extends JPanel implements ActionListener {

    public JButton b[] = new JButton[8];  // 8 Buttons
    public boolean bp[] = new boolean[8]; // the state of each button, pressed or not

    //constructor
    public ButtonPanel() {
        //create GUI

        setLayout(new GridLayout(8, 1));

        //create all the 8 buttons and register button to listener event
        for (int i = 1; i <= b.length; i++) {
            b[8 - i] = new JButton("F" + Integer.toString(8 - (i - 1)));
            b[8 - i].setBackground(Color.cyan);
            b[8 - i].addActionListener(this);
            add(b[8 - i]);
        }
    }

    public void actionPerformed(ActionEvent e) {
        //handle the button pressing events
        int buttonNumber = Integer.parseInt(String.valueOf(e.getActionCommand().charAt(1)));

        if(bp[8 - buttonNumber] = true) {
        System.out.println(bp[8 - buttonNumber]);
        b[buttonNumber-1].setBackground(Color.red);
        }
    }
} //the end of ButtonPanel class

// The elevator class draws the elevator area and simulates elevator movement
class Elevator extends JPanel implements ActionListener {
    //Declaration of variables

    private Elevator_Simulation app; //the Elevator Simulation frame
    private boolean up; // the elevator is moving up or down
    private int width;  // Elevator width
    private int height; // Elevator height
    private int xco;	// The x coordinate of the elevator's upper left corner
    private int yco; // The y coordinate of the elevator's upper left corner
    private int dy0; // Moving interval
    private int topy; //the y coordinate of the top level
    private int bottomy; // the y coordinate of the bottom level
    private Timer tm; //the timer to drive the elevator movement
    //other variables to be used ...

    //constructor
    public Elevator(Elevator_Simulation app) {
        //necessary initialization
        dy0 = 10;
        tm = new Timer(1000, this);
        tm.start();
    }

    // Paint elevator area
    public void paintComponent(Graphics g) {

        width = getWidth() / 8;
        height = getHeight() / 8;
        //put elevator in middle and bottom floor
        xco = getWidth() / 2 - 45 ;
        yco = height * 7;
        topy = 0;
        bottomy = height * 7;

       //clear the painting canvas
        super.paintComponent(g);
        //start the Timer if not started elsewhere
        if (!tm.isRunning()) {
            tm.start();
        }

        //draw horizontal lines and the elevator
        for (int i = 0; i <= 8; i++) {
            g.setColor(Color.red);
            g.drawLine(0, height * i, getWidth(), height * i);
        }
        g.setColor(Color.GRAY);
        g.fillRect(xco, yco, width, height);
        g.setColor(Color.RED);
        g.drawLine(xco + (width / 2), yco, xco + (width / 2), (yco + height));
    }



       //Handle the timer events
      public void actionPerformed(ActionEvent e) {
       
        //loop if the elevator needs to be stopped for a while

        //adjust Y coordinate to simulate elevator movement
        if(up) {
            yco -= dy0;
            //System.out.println(yco);
          }
          else {
              yco += dy0;
          }

        //change moving direction when hits the top and bottom
        //repaint the panel
        repaint();
        //update the state of the elevator

    
    }
}
 //the end of Elevator class

Hope you guys able to give me feedback on how should i solve this problem or maybe give some advices. Thanks much.

Please re-post code in code tags so we can read it.

makes the timer does not work

What does not work?
Is the timer called when it should be? Add print outs to show that it is.
or is it the logic in the actionPerformed method that is wrong?
Again add print outs of all the variables to show how they are changing so you can see their values and understand where your logic is wrong.

Please re-post code in code tags so we can read it.

James please do not ask people to repost their code again, rather advise on using code tags for future posting. As you know multi-posting is against forum rules

James please do not ask people to repost their code again, rather advise on using code tags for future posting. As you know multi-posting is against forum rules

Sorry.

No problem, I'm just trying to keep it clean here ;)

What does not work?
Is the timer called when it should be? Add print outs to show that it is.
or is it the logic in the actionPerformed method that is wrong?
Again add print outs of all the variables to show how they are changing so you can see their values and understand where your logic is wrong.

hi there,

thanks for the reply.

yes..i tried to test the timer using actionperformed event by doing simple system.out.println("timer is working");

i think the problem lies with the logic. what i dont understand is when i tried to declare variables yco = height * 7; in this case, it will be the y coordinate of the elevator, it will show the elevator at the bottom floor. (attached the compilation under jpeg)

But this declaration will not make the timer work up / down the elevator.

tried to test the timer

You don't say if the timer is being called or not. Is it?

i think the problem lies with the logic

Yes that could be. Have you tried debugging your code by adding print outs of all the variables to see how they change? When you see how they change you should be able to compare the computer's generated values with the values you know the program needs to generate to work properly.

You don't say if the timer is being called or not. Is it?

Yes that could be. Have you tried debugging your code by adding print outs of all the variables to see how they change? When you see how they change you should be able to compare the computer's generated values with the values you know the program needs to generate to work properly.

i did test it by using command isRunning().

yep i did so. just i dont understand why when i declare yco variables under paint component(graphic g) it will make the elevator just stay at one place..not moving up down. Any advice on this. i tried debug also. seems no issue. Thanks.

i did test it by using command isRunning().

You still don't say if it is working or not.

You must debug the code to see why it is not doing what you want it to do.

For example what variable(s) need to change for the elevator to be drawn at a different floor? Where does you code change the variable? What values does it give that variable?

An easy way to see what is happening to the variables is to print out there values.

Hi,

the timer is working. which lines of codes should i debug?all?

Start with the controlling variable for the elevator moving:
what variable(s) need to change for the elevator to be drawn at a different floor? Where does you code change the variable? What values does it give that variable?

actually i realised without give value to variables yco it will be able to moving but the problem is once i set the yco (elevator) to reside at bottom floor..it will not moving at all. any advice or pointer to give which lines of codes i should change?

Change the values of the yco variable to make the program do what you want it to do.
What should be the initial value? What values should you change it to for the elevator to move as you want?

hi,

previously i change the yco value to 196. it does make it to the bottom floor of the elevator area.but how do i make it using getHeight() of the frame only? because using static value does not seem right even thought its correct. thanks for the advice.

how do i make it using getHeight() of the frame only

I think you need to wait until the frame is visible before you can get its height.

using static value does not seem right even thought its correct

Sorry, I don't understand what you are asking.

Hi there,

i finally able to make the elevator moving but when it tries to go down..its stuck..here are the codes.

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


    //constructor
    public Elevator_Simulation() {
        // Create GUI

        //container for all the panels
        Container container = getContentPane();
        //name and group (with a color)
        id = new JLabel("Name : Anthony Salim Kwang", SwingConstants.CENTER);
        id.setForeground(Color.red);
        JPanel id_panel = new JPanel();
        id_panel.add(id);
        container.add(id, BorderLayout.NORTH);

        //all the 8 buttons panel
        control = new ButtonPanel();
        JPanel control_panel = new JPanel();
        control_panel.add(control);
        container.add(control, BorderLayout.WEST);

        //state of elevator (up/down)
        state = new JLabel("elevator up/down", SwingConstants.CENTER);
        JPanel state_panel = new JPanel();
        state_panel.add(state);
        container.add(state, BorderLayout.SOUTH);

        elevator = new Elevator(this);
        JPanel elevator_panel = new JPanel();
        elevator_panel.add(elevator);
        container.add(elevator, BorderLayout.CENTER);

    }

    // Main method
    public static void main(String[] args) {
        // Create a frame and display it

        Elevator_Simulation frame = new Elevator_Simulation();
        frame.setTitle("lab1: Elevator Simulation");
        frame.setSize(400, 300);

        //center the frame
        frame.setLocationRelativeTo(null);
        //exit upon closing
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
} //the end of Elevator_Simulation class

//The ButtonPanel class receives and handles button pressing events
class ButtonPanel extends JPanel implements ActionListener {

    public JButton b[] = new JButton[8];  // 8 Buttons
    public boolean bp[] = new boolean[8]; // the state of each button, pressed or not

    //constructor
    public ButtonPanel() {
        //create GUI

        setLayout(new GridLayout(8, 1));

        //create all the 8 buttons and register button to listener event
        for (int i = 1; i <= b.length; i++) {
            b[8 - i] = new JButton("F" + Integer.toString(8 - (i - 1)));
            b[8 - i].setBackground(Color.cyan);
            b[8 - i].addActionListener(this);
            add(b[8 - i]);
        }
    }

    public void actionPerformed(ActionEvent e) {
        //handle the button pressing events
        int buttonNumber = Integer.parseInt(String.valueOf(e.getActionCommand().charAt(1)));

        if(bp[8 - buttonNumber] = true) {
        System.out.println(bp[8 - buttonNumber]);
        b[buttonNumber-1].setBackground(Color.red);
        }
    }
} //the end of ButtonPanel class

// The elevator class draws the elevator area and simulates elevator movement
class Elevator extends JPanel implements ActionListener {
    //Declaration of variables

    private Elevator_Simulation app; //the Elevator Simulation frame
    private boolean up; // the elevator is moving up or down
    private int width;  // Elevator width
    private int height; // Elevator height
    private int xco;	// The x coordinate of the elevator's upper left corner
    private int yco; // The y coordinate of the elevator's upper left corner
    private int dy0; // Moving interval
    private int topy; //the y coordinate of the top level
    private int bottomy; // the y coordinate of the bottom level
    private Timer tm; //the timer to drive the elevator movement
    //other variables to be used ...

    //constructor
    public Elevator(Elevator_Simulation app) {
        //necessary initialization        

        yco = 196;
        dy0 = 10;
        up = true;

        this.app = app;
        tm = new Timer(100, this);
        tm.start();
       
    }

    // Paint elevator area
    public void paintComponent(Graphics g) {


        width = getWidth() / 8;
        height = getHeight() / 8;
        bottomy = height * 7;
        topy = 0;
        xco = getWidth() / 2 - 45;

       //clear the painting canvas
        super.paintComponent(g);
        //start the Timer if not started elsewhere
        if (!tm.isRunning()) {
            tm.start();
        }

        //draw horizontal lines and the elevator
        for (int i = 0; i <= 8; i++) {
            g.setColor(Color.red);
            g.drawLine(0, height * i, getWidth(), height * i);
        }

        g.setColor(Color.GRAY);
        g.fillRect(xco, yco, width, height);
        g.setColor(Color.RED);
        g.drawLine(xco + (width / 2), yco, xco + (width / 2), (yco + height));
    }

       //Handle the timer events
      public void actionPerformed(ActionEvent e) {
       
        //loop if the elevator needs to be stopped for a while

        //adjust Y coordinate to simulate elevator movement
        if(up && yco > bottomy) {
            yco -= dy0;
         
        }
        else {
            yco += dy0;
        }
        System.out.println(yco);
        //change moving direction when hits the top and bottom


        //repaint the panel
        repaint();
        //update the state of the elevator

    
    }
}
 //the end of Elevator class

when it tries to go down..its stuck

You need to continue debugging the code to see how the variables are changing.
What do you want the elevator to do? Why is it getting stuck?
What variable makes it get stuck? What can you do in your code to prevent that from happening?

I think you need to wait until the frame is visible before you can get its height.

Yep.the frame is set up to be visible.

Sorry, I don't understand what you are asking.

i assigned manually yco = 196. But if i use getHeight() i will not be able to make the elevator move because it will be declare under paint component. for your info in order to get getHeight() it must be declared in paint component. if i set it under elevator class, it will give return result of 0 (no value yet).

Thanks for any advices or feedback.

You can set it in paintComponent, but you only want to do it the first time. You can use a boolean to control that:
// Define this boolean at the class level

boolean firstTime = true; // used to execute code only the first time

Inside the paintComponent method;

if(firstTime) {
  yco = getHeight() ....
  firstTime = false; // turn off the flag, next time we'll skip this
}

Hi,

Thanks for the reply. i managed to do it using the boolean.

but when i tried to make it looping up down by doing this codes:

if(up && yco >= topy) {
            yco -= dy0;
            System.out.println(yco);
        }
        else {
            yco += dy0;
        }

it will goes up but stuck at the topy. any advice on the logic?thanks.

hi there,

i am now able to make the elevator up down already.thanks. its really feel great to be able to do it on your own. ^^

hope you will be able to give more advices or feedback on several issues i will face.thanks.

Glad you have figured it out.
Come on back when you have more problems.

hi there,

i encounter a new problem with the codes. currently i tried to ensure that the elevator stop at the right floor. but when i tried type this codes, it does not stop at exactly what i wanted.

//loop if the elevator needs to be stopped for a while
        if((yco == topy) && (app.control.bp[0] == true)) {
            tm.setDelay(100000);
        }

Any feedback appreciated.thanks.

does not stop at exactly what i wanted.

What is it that you wanted? Please explain what the problem is.

hi,

i tried to make the elevator stop when i press the button for example button 8. but the delay timer seem makes the elevator stop. How should i implement the timer delay so that it will make the elevator just stop awhile then continue running but not completely stop the elevator. thanks.

What is the Timer used for here?
Can you use another Timer to control how long the elevator waits on a floor? After the wait, the elevator will start moving again.

Timer here is used to control the elevator movement up / down. creating another timer object?

Have a Timer to control how long to wait.

yep. i do have timer object declared already.

i have:

tm = new Timer(100, this);

    //start the timer
    tm.start();[/CODE]

this is to start the timer.

so in order to stop elevator i was thinking of using tm.setDelay(1000) but somehow it does not stop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.