【问题标题】:mouseClicked event on a shape continually being repainted on a canvas形状上的 mouseClicked 事件不断在画布上重新绘制
【发布时间】:2016-04-11 01:47:50
【问题描述】:

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

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;
    }
}

【问题讨论】:

  • How to Write a Mouse Listener?你有什么理由使用Canvas?我只问,因为使用java.awt.Canvas 的主要原因是使用BufferStrategy,否则您可能应该使用JPanel 并免费获得双缓冲
  • 另外,你的事件处理真的,真的过时了
  • 您的基本问题也可能是计时器和事件调度线程之间的竞争条件,因此当您收到有关鼠标事件的通知时,它的位置已经更新。可能在关键区域周围使用 Swing Timer 或同步块可能会有所帮助
  • 我想我使用Canvas 的唯一原因是我在“绘画”时被教导要使用的东西。我的任何代码“过时”都不会让我感到惊讶。我已经有一段时间没有编码了。然而,我很高兴学习更好、更现代的做事方式。我以前没有使用过同步块。我会在那里做一些研究。

标签: java awt mouseclick-event


【解决方案1】:

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

我先看看Painting in AWT and SwingPerforming Custom PaintingHow to Write a Mouse Listener

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

虽然最先进的是使用 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

【讨论】:

  • 摇摆计时器肯定有助于鼠标事件,我正在将其合并到项目中。谢谢!
  • 感谢您花时间编写示例代码。里面有几件我以前没用过的东西,所以我逐行检查以确保我掌握了正在发生的事情。除了资源链接之外,拥有示例也有所帮助……我明白了。但是,在阅读了键绑定材料后,我并没有感觉比以前更接近了。我相信你KeyListener 已经过时了,但它似乎更容易理解。我查阅了几篇关于键绑定的文章,但我的大脑并没有点击它。
  • 键绑定可能需要一些时间才能掌握,但它们代表了大型可重用代码元素Actions 的一部分,因此您可以将相同的Action 用于菜单项、按钮和/或键绑定,使其非常有用
  • 对于example,SO上有无数的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多