【问题标题】:MouseListener - not working on JTextAreaMouseListener - 不适用于 JTextArea
【发布时间】:2015-04-15 07:36:18
【问题描述】:

我有一个扩展 JFrame 的 Gui 类。顶部有一个 JMenuBar,其余由一个大的 JTextField 组成。

我已经为这个类实现了一个mouseListener,问题是它似乎只在单击JMenuBar 时才听,而不是JTextArea。所以我的问题是我如何让 mouseListener 对鼠标点击 JTextArea 做出反应

这是 Gui 类(构造函数)的快照

 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);

}

【问题讨论】:

  • 为什么MouseListener 应该对JFrame(您注册它的地方)发生的鼠标事件以外的任何其他事件做出反应?五月How to Write a Mouse Listener可以帮忙
  • 您的问题至少有两种可能的解决方案,但您要使用哪种取决于您要实现的目标
  • @MadProgrammer - 哎呀,是的,你是对的。我怎么能错过呢?

标签: java swing jtextarea mouselistener


【解决方案1】:

将鼠标侦听器添加到文本区域而不是窗口。

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

【讨论】:

    猜你喜欢
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2021-10-17
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多