这是代码。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class Paint extends JPanel implements MouseMotionListener, MouseListener {
public Paint() {
setBackground(Color.RED);
addMouseMotionListener(this);
addMouseListener(this);
}
private boolean clicked = false;
public void paintComponent (Graphics g) {
super.paintComponent(g);
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX() - 3;
int y = (int) b.getY() - 23;
if (clicked) {
g.drawLine(x, y-5000, x,y+5000);
g.drawLine(x+5000,y,x-5000,y);
g.setColor(Color.white);
}
g.drawLine(x, y-5000, x,y+5000);
g.drawLine(x+5000,y,x-5000,y);
g.setColor(Color.black);
// . . .
}
@Override
public void mouseDragged(MouseEvent e) {
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
clicked = true;
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
clicked = false;
repaint();
}
}
public class Frame extends JFrame {
public Frame() {
this.setSize(500,500);
this.setTitle("Test painting");
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Paint panel = new Paint();
this.add(panel);
this.setVisible(true);
}
public static void main (String[] args) {
new Frame();
}
}
当我运行程序时,当应用程序处于默认位置时看起来它工作正常,但是一旦我将applet移动到屏幕上我喜欢的位置,这些行就不能保持当前鼠标在屏幕上的位置
有人能告诉我出错的地方或如何解决这个问题吗?
答案 0 :(得分:3)
绘画是从组件的上下文完成的。翻译任何给定组件的Graphics
上下文,使左上角为0x0。
MouseInfo.getPointerInfo().getLocation()
返回鼠标在屏幕上的位置,而不是相对于组件的位置。
虽然有办法解决它,但更好的解决方案是简单地使用MouseMotionListener
。发送到此方法的MouseEvent
已转换为组件坐标空间...
public void mouseMoved(MouseEvent me) {
myPoint = me.getPoint();
}
然后在您paintComponent
方法中,简单参考myPoint
而不是尝试使用MouseInfo
答案 1 :(得分:1)
我认为您最好在MouseAdapter中更改类的状态,调用repaint()
然后让paintComponent(...)
方法使用此状态来帮助它绘制。这比使用paintComponent(...)
中的MouseInfo更清晰,更安全。
除此之外,如果您需要更多具体帮助,请考虑