如何检测鼠标是否已向右或向左移动(未拖动)?

时间:2016-02-03 18:56:33

标签: java swing graphics

我知道MouseEvent类中的getX()函数,但是我无法使用它来检测左或右运动。 我正在做一个简单的Pong游戏,其中球可以通过鼠标的动作进行定向 我无法使用mouseMoved函数来确定鼠标的运动,无论是向右还是向左移动

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PongGame extends JComponent implements ActionListener,MouseMotionListener
{

    int ballX = 400;//ball's x location
    int ballY = 150;//ball's y location
    int paddleX = 0;//paddle loaction
    int ballXS = 10;//ball x speed
    int ballYS = 10;//ball y speed

    public static void main(String args[])
    {
        JFrame window = new JFrame("Game");
        PongGame game = new PongGame();
        window.add(game);
        window.pack();
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setLocationRelativeTo(null);
        window.setVisible(true);

        Timer t = new Timer(10, game);
        t.start();

        window.addMouseMotionListener(game);
    }

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

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 800, 600);

        g.setColor(Color.GREEN);
        g.fillRect(paddleX, 580, 150, 15);

        g.setColor(Color.YELLOW);
        g.fillOval(ballX, ballY, 10, 10);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        ballX += ballXS;
        ballY += ballYS;
        //simple direction of ball to bounce around the screen
        if (ballX >= paddleX && ballX <= paddleX + 150 && ballY >= 570)
        {
            ballYS = -10;
        }
        if (ballX >= 770)
        {
            ballXS = -10;
        }
        if (ballX <= 0)
        {
            ballXS = 10;
        }
        if (ballY <= 0)
        {
            ballYS = 10;
        }
        if (ballY > 600)
        {
            ballY = 0;
            ballX = 0;
        }
        repaint();
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {

    }

    @Override
    public void mouseMoved(MouseEvent e)
    {
        paddleX = e.getX() - 75;                
        int x1 = e.getX();        
        int x2 = e.getX();
        /*here i wanted to get a left or right motion by using x1 and x2
                so that ball can be directed accordingly*/

        repaint();
    }
}

1 个答案:

答案 0 :(得分:2)

 int x = e.getX();        
 /*here i wanted to get a left or right motion by using x1 and x2
            so that ball can be directed accordingly*/
 if(x>prevx) ballXS=10; // right
 if(x<prevx) ballXS=-10; // left
 prevx=x;

根据您的整个计划,prevx是一些全局变量。