Search code examples
javaswingjtextareamouselistener

MouseListener - not working on JTextArea


I have A Gui-class that extends JFrame. At the top there is a JMenuBar and the rest consists of a big JTextField.

I have implemented a mouseListener to this class and the problem is that it only seem to listen when clicking on the JMenuBar, not the JTextArea. So my question is how I make the mouseListener react to mouse click on the JTextArea

heres a snappshot of the Gui-class (constructor)

 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


Solution

  • Add Mouse Listener to the textarea instead of the window.

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