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?
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);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With