Raul Rao Raul Rao - 1 year ago 98
Java Question

Paint something in JFrame after an event occurred?

How can I paint something in a frame in an event handler in java? Because I want to write the game Breakout and there I would need to repaint the entire screen in the event handler.

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;
g.fillRect(x, y, paddle_width, paddle_height);

Answer Source

You can create your drawing panel extending JPanel and override the paintComponent.

Then you can have a model (By model i mean the data about what you want to paint)

Then you can add MouseMotionListener which would manipulate your model.

Notify the model changes to the drawing panel so that it will update the painting based on the model changes.

The below code should help you progress.

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();

    public Demo() throws HeadlessException {

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

    class DrawingPanel extends JPanel implements MouseMotionListener {

        private Paddle paddle;

        public DrawingPanel(Paddle paddle) {
            this.paddle = paddle;

        protected void paintComponent(Graphics g) {
            g.fillRect(paddle.point.x, paddle.point.y, paddle.width, paddle.height);

        public void mouseDragged(MouseEvent e) {


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


    class Paddle {
        Point point;
        Integer height, width;

        public Paddle(Point point, Integer height, Integer width) {
            this.point = point;
            this.height = height;
            this.width = width;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download