java形状没有在适当的位置绘制,在其他地方绘制2040像素(使用MouseStener)
当我试着在鼠标点击的地方画一个正方形时,这个正方形被画得离鼠标点击几像素远。不仅如此,当窗口第一次打开时,它似乎没有显示为1080乘720(黑色背景实际上是模糊的,你必须调整窗口的大小),这可能与此有关吗
我试着比较鼠标点击的位置和正方形的位置,但它们是一样的。点击一个点会使正方形移动到那里。。。或者它应该。。。(在Windows 10上运行此功能)。谢谢你的帮助
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Core extends JComponent implements MouseListener, ActionListener
{
private Timer timer;
private Player player;
public Core()
{
timer = new Timer(3, this);
timer.start();
player = new Player(500, 500, 30, 30, 1);
}
public static void main(String[] args)
{
JFrame window = new JFrame();
Core game = new Core();
window.add(game);
window.addMouseListener(game);
window.pack();
window.setSize(1080, 720);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.fillRect(0,0,1080,720);
if(timer.isRunning())
player.paint(g2);
}
@Override
public void mouseClicked(MouseEvent e)
{
player.setNewPosition(e.getX(), e.getY());
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
@Override
public void mouseExited(MouseEvent e)
{
}
@Override
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
import java.awt.*;
public class Player
{
private int x,y,width,length,speed;
private int newX, newY;
public Player(int x, int y, int width, int length, int speed)
{
this.x = x;
this.y = y;
this.width = width;
this.length = length;
this.speed = speed;
newX = x;
newY = y;
}
public void setNewPosition(int newX, int newY)
{
this.newX = newX;
this.newY = newY;
}
public void move()
{
if(x > newX)
x -= speed;
else if(x < newX)
x += speed;
if(y > newY)
y -= speed;
else if(y < newY)
y += speed;
}
public void paint(Graphics2D g2) //paint method
{
g2.setColor(Color.blue);
move();
g2.fillRect(x, y, width, length);
}
}
# 1 楼答案
改变
更像是
MouseEvent
使用的坐标将相对于source
的坐标空间就我个人而言,我会在
Core
的构造函数中注册MouseListener
,但你明白了