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) {};
}
------解决方案--------------------
加这句再试:
textArea.addMouseListener(this);