Reputation: 31724
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?
Upvotes: 3
Views: 2020
Reputation: 8806
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);
}
});
}
Upvotes: 1
Reputation: 32323
You've shown the wrong portion of the code. The part of the code that matters is your MouseListener
, i.e. what happens when you rightclick.
In that MouseEvent
, you can check the selection of your JTextPane
, using JTextComponent.getSelectedText(), i.e.
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
}
}
}
Upvotes: 1