Avatar of peiling82
peiling82
 asked on

How to use timer to do the movement an object


Hi Expert,

I'm currently doing a java project.

May i noe how to use timer to set the movement of an object, etc. rectangle.

Just for info, i'm doing a evalator simulation which i need to click a button for the user to go to. And i need to further improve the speed of the movement by allow user to speed up the movement.

Pls advice.

Thanx.

Regards,
peiling82
Game ProgrammingProgramming

Avatar of undefined
Last Comment
nonubik

8/22/2022 - Mon
nonubik

You can move the object inside the time handler function.
When user speeds up the movement, you'll kill the current timer and set a new one (with the same ID) that will have a shorten timeout value. This inside the handler for the speed control.
peiling82

ASKER
In the 1st place,
b4 i proceed to speed up the timer,

may i noe how to write the function to redraw the rect(lift)
in a new location and repaint()?

Can give some code?

Thanx.
nonubik

How do you draw it in the first place?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
peiling82

ASKER
Do you wan me to send u my code?
nonubik

Yep, some code.
I mean, do you use GDI functions?
peiling82

ASKER
Do u mind to give me ur email address?
I send my code to u...
Is very simple coding....

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
nonubik

No email.
The idea is to remove the rect from the first location and draw it to the next one.
peiling82

ASKER
import java.awt.*;
import javax.swing.*;


/*** Create a rectangle box as the elevator*****/
class RectPanel extends JPanel
{
public int x, initialY, y;
protected void paintComponent(Graphics g)
{
super.paintComponent(g);      

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
            
x = getWidth()/2-20;
initialY = getWidth()/2-20;
            
//set new color
g.setColor(Color.black);
                        
//draw a rectangle
g.drawRect(x,y,40,23);
g.fillRect(x,y,40,23);
            
}

public void setNewY()
{
      y = y - 10;
      repaint();
}
}

Above are my code for the rectangle. The rectangle currently is static and cannot move.

My problem is how to remove it and redraw?

Thanx
ASKER CERTIFIED SOLUTION
nonubik

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.