JAVA 该怎么添加鼠标事件的监听器

importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjavax.swing.event.*... import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPicture extends JFrame implements MouseListener
{
JFrame frame;
JButton a1,a2,a3;
JPanel panel;
int mouseX,mouseY,sh=10,ss=290;
String msg="坐标:";
String setX,setY;
public MyPicture() //程序界面
{
frame=new JFrame("图形学实验");
a1=new JButton("直线");
a2=new JButton("弧");
a3=new JButton("裁剪");
panel=new JPanel();
panel.add(a1);
panel.add(a2);
panel.add(a3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void mouseEntered(MouseEvent me) //鼠标进入事件
{
mouseX=getX();
mouseY=getY();
setX=mouseX+"";
setY=mouseY+"";
msg=msg+setX+" "+setY;
repaint();
}
}
public void mousePressed(MouseEvent me){}
public void mouseReleased(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mouseClicked(MouseEvent me){}
void paint(Graphics g) //显示鼠标坐标
{
g.drawString(msg,sh,ss);
}
public static void main(String[] args)
{
MyPicture org=new MyPicture();
addMouseListener(this);
}
}
展开
 我来答
65288664
推荐于2018-03-11 · TA获得超过952个赞
知道小有建树答主
回答量:2359
采纳率:0%
帮助的人:1111万
展开全部
这样子写比较好
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPicture extends JFrame
{
JFrame frame;
JButton a1,a2,a3;
JPanel panel;
int mouseX,mouseY,sh=10,ss=290;
String msg="坐标:";
String setX,setY;
public MyPicture() //程序界面
{
frame=new JFrame("图形学实验");
a1=new JButton("直线");
a2=new JButton("弧");
a3=new JButton("裁剪");
panel=new JPanel();
panel.add(a1);
panel.add(a2);
panel.add(a3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
addMouseListener(new MouseMonitor());
}

public void paint(Graphics g) //显示鼠标坐标
{
g.drawString(msg,sh,ss);
}

class MouseMonitor implements MouseListener {
public void mouseEntered(MouseEvent me) //鼠标进入事件
{
mouseX=getX();
mouseY=getY();
setX=mouseX+"";
setY=mouseY+"";
msg=msg+setX+" "+setY;
repaint();
}

public void mousePressed(MouseEvent me){}
public void mouseReleased(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mouseClicked(MouseEvent me){}
}

public static void main(String[] args)
{
MyPicture org=new MyPicture();
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式