一个形状上的mouseClicked事件不断在画布上重新绘制

时间:2016-04-11 01:47:51

标签: java awt mouseclick-event

我不断重新绘制一个圆圈以显示动画。如果点击,我想让圆圈闪烁不同的颜色。当我尝试实现MouseListener来获取mouseClicked事件时,它不起作用。我相信这是由于不断重新粉刷。有没有另一种方法让这个圆圈反弹并仍然抓住鼠标?我添加了一个KeyEvent来测试,它运行正常。没有“主要”,因为这是从另一个程序调用的。

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Timer;

public class Catch extends Canvas {

    int xCor, yCor, xMove, yMove;
    Color currentColor;
    Random ranNumber;
    boolean flashing = false;

    public Catch() {
        enableEvents(java.awt.AWTEvent.KEY_EVENT_MASK);
        requestFocus();
        xCor = 500;
        yCor = 350;
        xMove = 5;
        yMove = 5;
        currentColor = Color.black;
        ranNumber = new Random();
        Timer t = new Timer(true);
        t.schedule(new java.util.TimerTask() {
            public void run() {
                animate();
                repaint();
            }
        }, 10, 10);

    }

    public void paint(Graphics g) {
        g.setColor(currentColor);
        g.fillOval(xCor, yCor, 20, 20);
    }

    public void processKeyEvent(KeyEvent e) {
        if (e.getID() == KeyEvent.KEY_PRESSED) {
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                flashing = !flashing;
            }
        }
    }

    public void animate() {
        xCor += xMove;
        yCor += yMove;

        // and bounce if we hit a wall
        if (xCor < 0 || xCor + 20 > 1000) {
            xMove = -xMove;
        }
        if (yCor < 0 || yCor + 20 > 700) {
            yMove = -yMove;
        }

        if (flashing) {
            int r = ranNumber.nextInt(256);
            int g = ranNumber.nextInt(256);
            int b = ranNumber.nextInt(256);
            currentColor = new Color(r, g, b);
        }
    }

    public boolean isFocusable() {
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

您的方法有点过时,我们不再倾向于使用enableEvents,而是使用了许多不同的观察者&#34;提供有关某些事件的通知。

我首先看看Painting in AWT and SwingPerforming Custom Painting以及How to Write a Mouse Listener

我也避免使用KeyListener,而是使用旨在克服KeyListener的许多缺点的Key Bindings API。

虽然前沿将是使用JavaFX,但如果您对AWT有所了解,那么升级到Swing会更简单,例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Ball ball;

        public TestPane() {
            ball = new Ball();
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    ball.update(getSize());
                    repaint();
                }
            });
            timer.start();

            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    ball.setHighlighted(ball.wasClicked(e.getPoint()));
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            ball.paint(g2d);
            g2d.dispose();
        }

    }

    public class Ball {

        private int radius = 10;
        private int xDelta, yDelta;
        private Ellipse2D shape = new Ellipse2D.Double(0, 0, radius * 2, radius * 2);
        private boolean highlighted;
        private int cycleCount;

        public Ball() {
            Random rnd = new Random();
            xDelta = rnd.nextInt(3) + 1;
            yDelta = rnd.nextInt(3) + 1;
        }

        public void update(Dimension bounds) {
            Rectangle shapeBounds = shape.getBounds();
            shapeBounds.x += xDelta;
            shapeBounds.y += yDelta;
            if (shapeBounds.x + shapeBounds.width > bounds.width) {
                shapeBounds.x = bounds.width - shapeBounds.width;
                xDelta *= -1;
            } else if (shapeBounds.x < 0) {
                shapeBounds.x = 0;
                xDelta *= -1;
            }
            if (shapeBounds.y + shapeBounds.height > bounds.height) {
                shapeBounds.y = bounds.height - shapeBounds.height;
                yDelta *= -1;
            } else if (shapeBounds.y < 0) {
                shapeBounds.y = 0;
                yDelta *= -1;
            }
            shape.setFrame(shapeBounds);

            if (highlighted) {
                cycleCount++;
                if (cycleCount > 12) {
                    highlighted = false;
                }
            }
        }

        public boolean wasClicked(Point p) {
            return shape.contains(p);
        }

        public void setHighlighted(boolean value) {
            highlighted = value;
            cycleCount = 0;
        }

        public void paint(Graphics2D g) {
            if (highlighted) {
                g.setColor(Color.RED);
            } else {
                g.setColor(Color.BLUE);
            }
            g.fill(shape);
        }
    }

}

您还应该查看How to use Swing Timers