没有回应我的代码

时间:2012-11-20 17:29:43

标签: java event-handling applet mouseevent paintcomponent

我试图学习applet并执行此代码,没有编译时错误,但问题是我没有得到任何响应我的代码。我使用简单的记事本和appletviewer来完成它。单击小程序时,应显示坐标但不会发生。我尝试输入相关的html代码并通过浏览器执行但响应是相同的。任何帮助将非常感谢

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyMouseApplet.class"
width = "400"
height = "400"> 
</applet>*/

public class MyMouseApplet extends Applet implements MouseListener{
int x,y;
String str=" ";
public void init(){
this.addMouseListener(this);
}
public void paint(Graphics g){
g.drawString(str,x,y);
}
public void update(Graphics g){
paint(g);
}
public void mouseClicked(MouseEvent m)
{
int x = m.getX();
int y = m.getY();
str="x:" + x + "y:" + y;
repaint();
}
public void mouseExited(MouseEvent m){}
public void mouseEntered(MouseEvent m){}
public void mousePressed(MouseEvent m){}
public void mouseReleased(MouseEvent m){}
}

1 个答案:

答案 0 :(得分:0)

您的mouseClicked功能需要xy超出范围。这样做:

public void mouseClicked(MouseEvent m)
{
     //int x = m.getX();
     //int y = m.getY();
     x = m.getX();
     y = m.getY();
     str="x:" + x + "y:" + y;
     repaint();
}

这将访问您班级的字段,而不是本地变量。