右键单击以选择文本JTextPane

时间:2012-11-20 13:49:45

标签: java swing

在我的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);
}

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

2 个答案:

答案 0 :(得分:1)

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

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

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
         }
    }
}

答案 1 :(得分:1)

PopupMenuListener可以解决问题。

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