3

在我的 JTextPane 中,当我选择文本并右键单击时;它提供了复制文本的选项。下面是代码:

public LogPane() {
    super();
    JPopupMenu pop = new JPopupMenu();
    final LogPane l = this;
    JMenuItem copy = new JMenuItem("Copy      CTRL+C");
    copy.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            selected = l.getSelectedText();
            if(selected==null)
                return;
            StringSelection clipString = new StringSelection(selected);
            clipbd.setContents(clipString,clipString);
        }

    }); 
    pop.add(copy);
    copy.setEnabled(true);
}

因此,在右键单击时,它提供了复制文本的选项。但我想要的是,当没有选择文本并且用户右键单击时,不应该显示复制选项。应如何纳入更改?

4

2 回答 2

1

您显示了错误的代码部分。重要的代码部分是你的MouseListener,即当你右键单击时会发生什么。

在那MouseEvent,您可以检查您的选择JTextPane,使用JTextComponent.getSelectedText(),即

public void MouseClicked(MouseEvent me) {
    if(me.getButton() == MouseEvent.BUTTON2) {
         // This is the code you probably don't have yet
         // You may have to check this cast
         JTextComponent myComponent = (JTextComponent) me.getComponent();
         if (myComponent.getSelectedText() != null) {
             JPopupMenu theMenu = myComponent.getComponentPopupMenu();
             // Etc... you wrote this part already and said it works
         }
    }
}
于 2012-11-20T14:04:48.613 回答
1

APopupMenuListener应该做的伎俩。

public LogPane() {
    super();
    JPopupMenu pop = new JPopupMenu();
    final LogPane l = this;
    final JMenuItem copy = new JMenuItem("Copy      CTRL+C");
    copy.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            selected = l.getSelectedText();
            if(selected==null)
                return;
            StringSelection clipString = new StringSelection(selected);
            clipbd.setContents(clipString,clipString);
        }

    }); 
    pop.add(copy);
    pop.addPopupMenuListener(new PopupMenuListener() {
        public void popupMenuCanceled(PopupMenuEvent e) {}
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            copy.setEnabled(l.getSelectedText() != null);
        }
    });
}
于 2012-11-20T14:07:59.490 回答