JMenuBar/JMenuItem and JTextPane: Focus Owner Problem for Cut/Copy/Paste/Select All

When using JMenuItem in JMenuBar to cut/copy/paste/select all text from a JTextPane, a focus from JTextPanel is temporarily lost to JMenuItem. The loss of focus causes isFocusOwner() of JTextPane to return false. As a result, the cut/copy/paste/select all methods using JMenuItem do not work.

For example, I use JMenuItems for cut/copy/paste/select all methods with the following names, cutMenuItem, copyMenuItem, pasteMenuItem and selectAllMenuItem. I have two JTextPanes, one is source and another is target. I want to allow a user to cut/copy/select all text from one JTextPane and paste it into another JTextPane.

I implement my cutText() method as follows.


public void cutText(){

if(sourceWindowTextPane.isFocusOwner()){

sourceWindowTextPane.cut();

}

else if(targetWindowTextPane.isFocusOwner()){

targetWindowTextPane.cut();

}

}

The problem with the above method is that when a user clicks on the cutMenuItem, a focus of sourceWindowTextPane or targetWindowTextPane is temporarily transfered to cutMenuItem. Accordingly, isFocusOwner() method returns false for both sourceWindowTextPane and targetWindowTextPane.

There are two working solutions to this lost focus problem.

1) Get focus owner name and compare with JTextPane name

public void cutText(){

String focusOwnerName=this.getContext().getFocusOwner().getName();

if (focusOwnerName.equalsIgnoreCase("sourceWindowTextPane")) {

sourceWindowTextPane.cut();

} else if (focusOwnerName.equalsIgnoreCase("targetWindowTextPane")) {

targetWindowTextPane.cut();

}

}

2) Use KeyboardFocusManager to find the current permanent focus owner (Thanks to uncle_alice from Java swing forum).


public boolean isPermanentFocusOwner(Component comp)
{

return KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner() == comp;

}


public void cutText() {

if (isPermanentFocusOwner(sourceWindowTextPane)) {

sourceWindowTextPane.cut();

} else if (isPermanentFocusOwner(targetWindowTextPane)) {

targetWindowTextPane.cut();

}

}

Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s