[英]Java mouseListener's mousemove not working
I am trying to make a plotting program, the program should show the point the user is currently on, i tried using mousemove for this function (using console for now to view result) but it's not working. 我正在尝试制作一个绘图程序,该程序应该显示用户当前所在的点,我尝试使用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());
}
}
Thanks in Advance 提前致谢
MouseListener
does not have a mouseMoved
method. MouseListener
没有mouseMoved
方法。
You have to add the declaration that you are going to also implement the Mouse Motion Listener interface: 您必须添加将要实现Mouse Motion Listener接口的声明:
public class drawArea extends JPanel
implements MouseListener, MouseMotionListener
Additionally, you have to add this mouse motion listener in the constructor 此外,您必须在构造函数中添加此鼠标动作侦听器
this.addMouseMotionListener(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.