事件发生后在JFrame中绘制一些东西?

时间:2016-06-22 08:15:45

标签: java swing mouseevent paint

如何在java中的事件处理程序中绘制框架中的内容?因为我想编写游戏Breakout,我需要在事件处理程序中重新绘制整个屏幕。

    public void mouseMoved(MouseEvent e, Graphics g)
    {
        // if mouse was moved then rearrange paddle 
        double x = e.getX() - paddle_width;
        double y = e.getY() - paddle_height;
        this.repaint();
        g.setColor(Color.BLACK); 
        g.fillRect(x, y, paddle_width, paddle_height);
    }

1 个答案:

答案 0 :(得分:2)

您可以创建扩展JPanel的绘图面板并覆盖paintComponent。

然后你可以有一个模型(模型我的意思是关于你想要绘制的数据)

然后你可以添加操作模型的MouseMotionListener。

将模型更改通知到绘图面板,以便它将根据模型更改更新绘画。

以下代码可以帮助您取得进展。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Demo extends JFrame {

    public static void main(String[] args) {
        Demo frame = new Demo();
        frame.setVisible(true);
    }

    public Demo() throws HeadlessException {
        super();
        init();
    }

    private void init() {
        Point start = new Point(0, 0);
        Paddle paddle = new Paddle(start, 20, 20);
        DrawingPanel drawingPanel = new DrawingPanel(paddle);
        setContentPane(drawingPanel);
        pack();
    }

    class DrawingPanel extends JPanel implements MouseMotionListener {

        private Paddle paddle;

        public DrawingPanel(Paddle paddle) {
            super();
            this.paddle = paddle;
            this.addMouseMotionListener(this);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLACK);
            g.fillRect(paddle.point.x, paddle.point.y, paddle.width, paddle.height);
        }

        @Override
        public void mouseDragged(MouseEvent e) {

        }

        @Override
        public void mouseMoved(MouseEvent e) {
            paddle.point = new Point(e.getX(), e.getY());
            repaint();
        }

    }

    class Paddle {
        Point point;
        Integer height, width;

        public Paddle(Point point, Integer height, Integer width) {
            super();
            this.point = point;
            this.height = height;
            this.width = width;
        }
    }
}