2015-04-15 103 views
2

我有一個擴展JFrame的Gui類。頂部有一個JMenuBar,其餘的由一個大的JTextField組成。MouseListener - 無法處理JTextArea

我已經實現了這個類的mouseListener,問題在於它只能在JMenuBar而不是JTextArea上單擊時進行監聽。所以我的問題是如何讓MouseListener的反應鼠標點擊了GUI類的JTextArea

繼承人snappshot(構造函數)

public class Gui extends JFrame implements ActionListener, MouseListener { 

private JMenu fileMenu; 
private JTextArea textArea; 
private JFileChooser chooser; 

public static void main(String[] args) { 

    new Gui().setVisible(true); 

} 

public Gui() { 

    setSize(600, 600); 
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
    setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); 

    createFileMenu(); 

    JMenuBar menuBar = new JMenuBar(); 
    setJMenuBar(menuBar); 
    menuBar.add(fileMenu); 

    textArea = new JTextArea(); 

    JScrollPane scroll = new JScrollPane (textArea, 
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 

    Container contentPane = getContentPane(); 
    contentPane.add(scroll); 

    chooser = new JFileChooser(); 

    addMouseListener(this); 

    setDefaultCloseOperation(EXIT_ON_CLOSE); 

} 

Screenshot

+0

爲什麼'MouseListener'會對'JFrame'(你註冊它的地方)出現的鼠標事件做出反應?可能[如何編寫鼠標監聽程序](http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html)可以提供幫助 – MadProgrammer

+0

至少有兩種可能的解決方案來解決您的問題,但是您希望使用將取決於你試圖實現什麼 – MadProgrammer

+0

@MadProgrammer - 哎呀,是的,你是對的。我怎麼會想念那個? – java

回答

3

添加鼠標監聽到textarea的,而不是的窗戶。

textArea = new JTextArea(); 
textArea.addMouseListener(this); 
+0

有很好的抓住:-) – java