Moving a rectangle with a button click
I have been delaying asking for help for a while now but now it just seems undoable. The problem that I am stuck on is to move a rectangle graphic at the click of a button. Upon clicking the "Send" button, the ActionListener attached to the "Send" button should cause a rectangle shape to move from the top of the frame to the bottom. I would really appreciate if you guys steer me in the right direction. Thanks
Re: Moving a rectangle with a button click
I'm been trying to do something like this just recently. I'm trying to do it by scheduling a panel.repaint(). My program sets the coordinates of the image with the mouses current position.
I haven't been able to get it to work yet.
You may want to take a look at this:
ScheduledExecutorService – Java program example « pradeepwiki
Re: Moving a rectangle with a button click
I just read your post again. It seems I misunderstood. But you'll still want to use a timer or scheduling to move the object. At each period you will update the position of the object and then call panel.repaint (or whatever your painting to).
Re: Moving a rectangle with a button click
you need to create a swing Timer like:
Code:
Timer time = new Timer(40, this);
Your class must implement the interface ActionListener
call your rapaint() method in your actionPerformed method.
you need a variable for your change lets say in x.
Code:
public void actionPerformed(ActionEvent arg0)
{
dx += 50;
repaint();
}
Code:
public void paint(Graphics g)
{
g.drawRect(dx, 100, 50, 50);
}
this scenario would redraw the rectangle 50 pixels to the right every 40 milliseconds.
hope it helps!
Re: Moving a rectangle with a button click
I miss read. To do this on button click you would do your dx += 50; in your button click event. I also forgot you need to start the timer:
Re: Moving a rectangle with a button click
Quote:
Originally Posted by
mwr1976
Your class must implement the interface ActionListener
Wrong. And a gentle nudge in the right direction would have been better than posting code, especially when the person asking the question hasn't posted his/her attempts at a solution.
db
Re: Moving a rectangle with a button click
Quote:
Originally Posted by
mwr1976
To do this on button click you would do your dx += 50; in your button click event.
What's a button click event? Are you sure you're posting advice that pertains to Java?
db