我正在尝试制作一个绘图程序,该程序应该显示用户当前所在的点,我尝试使用mousemove来实现此功能(现在使用控制台查看结果)但是它无效。
public class drawArea extends JPanel implements MouseListener {
Image img;
int w=580;
int h=580;
String equation = "";
int clicks = 0;
public drawArea(){
init();
this.addMouseListener(this);
}
private void init(){
setPreferredSize( new Dimension( w, h ) );
setVisible(true);
img = new ImageIcon("assets/Graph.png").getImage();
}
private void initializeGrid(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, this);
}
private void drawFunction(Graphics g, String function) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
double p=0.01; //plotting precision
for(double x=-5;x<5;x+=p){
int drawingX1=gx((x));
int drawingY1=gy(f(x));
int drawingX2=gx(x+p);
int drawingY2=gy(f(x+p));
g2d.drawLine(drawingX1, drawingY1, drawingX2, drawingY2);
}
}
private double f(double x){
return x*x;
}
private int gx(double x){
return (int) ((x+5)*(w/10));
}
private int gy(double y){
return (int) (h-(y+5)*(h/10));
}
public void setEquation(String equ){
equation=equ;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
initializeGrid(g);
drawFunction(g,"Function");
}
public void mouseClicked(MouseEvent e) {
if(clicks<3){
MainUI.points[clicks][0] = e.getX();
MainUI.points[clicks][1] = e.getY();
System.out.println(e.getX()+","+e.getY());
System.out.println(MainUI.points[clicks] [0]+","+MainUI.points[clicks][1]);
clicks++;
}
}
public void mouseEntered(MouseEvent e) {
//not needed
}
public void mouseExited(MouseEvent arg0) {
//not needed
}
public void mousePressed(MouseEvent arg0) {
//not needed
}
public void mouseReleased(MouseEvent arg0) {
//not needed
}
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX()+","+e.getY());
}
}
先谢谢
答案 0 :(得分:5)
MouseListener
没有mouseMoved
方法。
您必须添加声明,您还要实现鼠标 Motion 侦听器界面:
public class drawArea extends JPanel
implements MouseListener, MouseMotionListener
此外,您必须在构造函数
中添加此鼠标 motion 侦听器this.addMouseMotionListener(this);