JAVA鼠标事件类的一个问题?

来源:百度知道 编辑:UC知道 时间:2024/06/01 02:18:21
import java.awt.event.*;
import java.awt.*;
public class app34 extends Frame
{ static TextField tf=new TextField(20);
static Button bun=new Button("拖动我");
static int px,py,ox,oy,offx,offy,x,y;
public static void main(String args[])
{app34 frm=new app34();
frm.setLayout(null);
frm.setTitle("鼠标事件的处理");
frm.setBounds(10,10,330,240);
tf.setBounds(60,200,200,20);
bun.setBounds(60,50,50,25);
tf.setEditable(false);
frm.add(tf);
frm.add(bun);
bun.addMouseMotionListener(new MyMouseMotionList());
bun.addMouseListener(new MyMouseList());
frm.setVisible(true);}
static class MyMouseList extends MouseAdapter
{public void mousePressed(MouseEvent e)
{px=e.getX();//取得鼠标按下时的X坐标
py=e.getY();//取得鼠标按下时的Y坐标
ox=bun.getLocation().x;//取得bun的左边界距窗口左边界的距离
oy=bun.getLocation().y;//取得bun的上边界距窗口上边界的距离
}
static clas

static class MyMouseMotionList extends MouseMotionAdapter
{public void mouseDragged(MouseEvent e)
{offx=px-ox;//offx为鼠标指针与命令按钮左边界的距离
offy=py-oy;//offy为鼠标指针与命令按钮上边界的距离
x=e.getX()-offx;//获得新的位置
y=e.getY()-offy;
String position="命令按钮放置在("+x+","+y+")的位置";
tf.setText(position);
bun.setLocation(x,y);
ox=x;oy=y;
}
}

把这个类提取出来就行了,不要放在另一个里面

修改了的地方在程序中标出了。不过,说一句,大哥,你写得真不是一般的乱哪!当然,里面的那些类的嵌套可能是你不小心写错了的,但整个程序的结构依然很“不平凡”嘛!很乱!

import java.awt.event.*;
import java.awt.*;
import javax.swing.JFrame;

public class app34 extends JFrame {

static TextField tf = new TextField(20);
static Button bun = new Button("拖动我");
static int px, py, ox, oy, offx, offy, x, y;

public static void main(String args[]) {
app34 frm = new app34();
frm.setLayout(null);
frm.setTitle(