好的,在您的应用程序屏幕上选择一个点。说,中心。将该点标记为锚点。
现在,将 a 添加MouseMotionListener
到您的屏幕并在鼠标移动时查找。你需要这个点来画一条线。第一个点是锚点。
现在,repaint()
每次鼠标移动时调用。
在 中paintComponent(Graphics g)
,使用g.drawLine(anchorX,anchorY,mouseX,mouseY)
来画线。由于paint()
是 before 调用的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();
}
});
}
}