代码如下,运行没有错,但是为什么MouseListener不响应?
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;public class MouseTrack implements MouseListener{
private JFrame myFrame;
private JTextArea textArea;

public MouseTrack(){
myFrame=new JFrame();

JTextArea textArea=new JTextArea();
textArea.setEditable(false);
JScrollPane scroll=new JScrollPane(textArea);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

myFrame.addMouseListener(this);

myFrame.add(scroll,BorderLayout.CENTER);

myFrame.setSize(600,400);
myFrame.setResizable(false);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}

public static void main(String args[]){
MouseTrack frame=new MouseTrack();
}

public void mouseClicked(MouseEvent e) {
System.out.println("***");
String button;
if(e.getButton()==e.BUTTON1){
button="左键";
}
else if(e.getButton()==e.BUTTON3){
button="右键";
}
else{
button="滚轮";
}
textArea.append("点击了"+button);
textArea.append("\n点击相对位置:x="+e.getX()+" y="+e.getY());
textArea.append("点击次数:"+e.getClickCount());
}

public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e) {};
}
MouserListener

解决方案 »

  1.   

    给你正确的代码
    package bbs0902;
    import java.awt.BorderLayout;
    import java.awt.event.*;import javax.swing.*;public class MouseTrack {
    private JFrame myFrame;
    private JTextArea textArea; public MouseTrack() {
    myFrame = new JFrame(); final JTextArea textArea = new JTextArea();
    //textArea.setEditable(false);
    JScrollPane scroll = new JScrollPane(textArea);
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); textArea.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    System.out.println("***");
    String button;
    if (e.getButton() == e.BUTTON1) {
    button = "左键";
    } else if (e.getButton() == e.BUTTON3) {
    button = "右键";
    } else {
    button = "滚轮";
    }
    textArea.append("点击了" + button);
    textArea.append("\n点击相对位置:x=" + e.getX() + " y=" + e.getY());
    textArea.append("点击次数:" + e.getClickCount());
    }
    }); myFrame.add(scroll, BorderLayout.CENTER); myFrame.setSize(600, 400);
    //myFrame.setResizable(false);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myFrame.setVisible(true);
    } public static void main(String args[]) {
    MouseTrack frame = new MouseTrack();
    }
    }
      

  2.   

    你的窗口有了 JTextArea ,你设置监听对象就应该设置 JTextArea 的,不应该设置 JFrame 的监听对象。另外,关于你写的监听代码可以写的更简短点,使用MouseAdapter。
    还有你写的关于鼠标点击的代码里面,分类也不是很清楚。
      

  3.   

    谢谢,刚学java,很多都不会,非常感谢!
      

  4.   

    能不能帮我看下这个问题在哪http://bbs.csdn.net/topics/390577793