Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right click to select text JTextPane

Tags:

java

swing

In my JTextPane, when i select the text and right click; It gives the option to copy text. Below is the code:

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

So on right click, it gives the option to copy text. But what I want is that, when no text is selected and the user right clicks- Copy option should not be shown. How should the change be incorporated?

like image 389
Jatin Avatar asked Jan 25 '26 20:01

Jatin


1 Answers

A PopupMenuListener should do the trick.

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);
        }
    });
}
like image 130
Richard Neish Avatar answered Jan 27 '26 11:01

Richard Neish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!