如何为鼠标制作线点?
我试图在java中指向一条线(Graphics2d)指向鼠标光标。它不是指向光标,而是指向相反的方向(如果光标在左侧,则线指向右侧,对于Y轴则相同)。这是我的代码:
import java.awt.Graphics;
import java.awt.Graphics2D;
public void paintChildren(Graphics g){
Graphics g2d2 = (Graphics)g;
int centerX = 16;
int centerY = 16;
deltaX = mouseX - centerX;
deltaY = mouseY - centerY;
double angle=Math.atan2(deltaY, deltaX);
g2d2.drawLine(16, 16, (int)Math.floor(deltaX + Math.cos(angle)), (int)Math.floor(deltaY + Math.sin(angle)));
}
答案 0 :(得分:2)
好的,在你的应用程序的屏幕上选择一个点。说,中心。将该点标记为锚点。
现在,在屏幕上添加MouseMotionListener
,并在鼠标移动时查找。你需要这一点画一条线。第一点是锚点
现在,每次鼠标移动时调用repaint()
。
在paintComponent(Graphics g)
中,使用g.drawLine(anchorX,anchorY,mouseX,mouseY)
绘制线条。由于在paint()
之前调用了repaint()
,因此您需要为这4个变量赋予一些初始值。
SSCCE:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LineFollower extends JFrame{
int anchorX = 0;
int anchorY = 0;
int mouseX = 0;
int mouseY = 0;
JPanel canvas = new JPanel(){
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent();
g.setColor(Color.RED);
g.drawLine(anchorX, anchorY, mouseX, mouseY);
}
};
public LineFollower(){
anchorX = 500 / 2;
anchorY = 500 / 2;
this.getContentPane().add(canvas);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
});
this.pack();
//this.setSize(500,500);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new LineFollower();
}
});
}
}