Java 2D MouseListener和Timer问题

时间:2014-01-12 16:59:54

标签: java swing timer mouselistener

我正在编写一个游戏,一次绘制一个矩形(给定一个计时器指定的时间间隔)而不破坏以前绘制的矩形,当玩家点击矩形时,它应该消失,分数应该增加。 / p>

无论玩家是否点击任何内容,矩形都应继续出现在JPanel上。

但是现在我似乎无法让矩形一次出现一个,我似乎无法删除玩家点击的特定矩形。

这是执行绘图的JPanel(我有另一个使用JFrame来包含此JPanel的类):

class Surface extends JPanel implements ActionListener, MouseListener
{
    private double[] xcorr = new double[20];
    private double[] ycorr = new double[20];
    private Rectangle2D.Double[] rectangles = new Rectangle2D.Double[20];
    private int count = 0;
    private int score = 0;

    public Surface()
    {
        initRectangles();

        initTimer();

        addMouseListener(this);
    }

    private void initRectangles()
    {
        Random r = new Random();

        for (int i = 0; i < rectangles.length; i++)
        {
            xcorr[i] = r.nextDouble() * (500-50);
            ycorr[i] = r.nextDouble() * (500-50);
            rectangles[i] = new Rectangle2D.Double();
            rectangles[i].setFrame(xcorr[i], ycorr[i], 50, 50);
        }
    }

        private void initTimer()
    {
        Timer timer;
                timer = new Timer(1000, this);
                timer.setInitialDelay(200);
                timer.start();
        }

    @Override
        public void actionPerformed(ActionEvent e)
    {
        count++;

        repaint(); // this is where I want the next Rectangle to be painted without destroying any previously painted rectangle
        }

    @Override
    public void mouseClicked(MouseEvent me)
    {
        double x = me.getX();
        double y = me.getY();

        for (int i = 0; i < rectangles.length; i++)
        {
            if (x > xcorr[i] && x < xcorr[i] + 50 && y > ycorr[i] && y < ycorr[i] + 50)
            {
                score++;

                remove(rectangles[i]); // this is where I want the rectangle that the player clicked to disappear
            }
        }
    }
    public void mousePressed(MouseEvent me) {}
    public void mouseReleased(MouseEvent me) {}
    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me) {}

        private void doDrawing(Graphics g)
        {
                initRectangles();

                Graphics2D g2d = (Graphics2D) g;

                RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

                g2d.setRenderingHints(rh);

                g2d.setColor(new Color(150, 150, 150));

                g2d.draw(rectangles[count]);
        }

        @Override
        public void paintComponent(Graphics g)
        {
                doDrawing(g);
        }
}

感谢任何帮助!

0 个答案:

没有答案