-1

我有一个扩展 JPanel 的类,并且已经绘制了一个矩形。现在已经创建了另一个类,它创建了一个 Frame 并在其上添加了 JPanel 类。现在,我想使用 MouseMotionListener 水平移动矩形。我怎么做?代码会更有帮助。:)

4

1 回答 1

0

Add the JPanel to the JFrame and allow it to fill the entire frame.

Next create a new class to hold the Rectangle data e.g.

class RectangleData {

    int x;
    int y;
    int width;
    int height;

    public RectangleData(int x, int y) {
        this.x = x;
        this.y = y;
        width = 10;
        height = 5;
    }

    public void draw(Graphics g) {
        g.drawRect(x, y, width, height);
    }

    public incX() { x++; }
    public incY() { y++; }
    public decX() { x--; }
    public decY() { y--; }

}

Attach the mouse listener to the JPanel and determine the direction with something like so:

Point lastPoint;
RectangleData rect;

private void mouseMoved(MouseEvent e) {
    if (e.getX() > lastPoint.x) rect.incX();
    else if (e.getX() < lastPoint.x) rect.decX();

    if (e.getY() > lastPoint.y) rect.incY();
    else if (e.getY() < lastPoint.y) rect.decY();

    repaint();
}

The repaint call triggers the Panel's paint method which should contain a call to the rectangle's draw method

于 2014-08-19T14:12:29.293 回答