RectangleMover.java
import java.awt.Dimension;
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 RectangleMover
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("A moving rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final RectangleComponent component = new RectangleComponent();
component.setPreferredSize(new Dimension(COMPONENT_WIDTH, COMPONENT_HEIGHT));
panel.add(component);
JButton button = new JButton("Move");
panel.add(button);
/*
TODO:
When this button is clicked, the rectangle should move
to the right and downward by ten pixels.
*/
frame.add(panel);
frame.setVisible(true);
}
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private static final int COMPONENT_WIDTH = 200;
private static final int COMPONENT_HEIGHT = 400;
}
Use the following file:
RectangleComponent.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
/**
This component displays a rectangle that can be moved.
*/
public class RectangleComponent extends JComponent
{
public RectangleComponent()
{
// The rectangle that the paint method draws
box = new Rectangle(BOX_X, BOX_Y,
BOX_WIDTH, BOX_HEIGHT);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(box);
}
/**
Moves the rectangle by a given amount.
@param x the amount to move in the x-direction
@param y the amount to move in the y-direction
*/
public void moveBy(int dx, int dy)
{
box.translate(dx, dy);
repaint();
}
private Rectangle box;
private static final int BOX_X = 0;
private static final int BOX_Y = 0;
private static final int BOX_WIDTH = 20;
private static final int BOX_HEIGHT = 30;
}