Jtextpane click to create popup menu effect on selection not as intended
I have a JTextPane sitting in a JFrame, with a popup menu that is assigned to the JTextPane through the JTextPane.setComponentPopupMenu method.
I want to give the JTextPane a "Word-like" popup behavior. By that I mean, if you right click outside of your current text selection, the caret will reposition to where you right clicked, with menu options that affect a text selection (such as cut, copy, or bold) disabled. If you right click within your current text selection, the popup will appear with options that effect text se开发者_运维技巧lection enabled, the text selection will persist, and the caret will not move.
The problem is I cannot seem to find where I can put the code that handles the selection change. I tried:
- Using the "PopupMenuWillBecomeVisible" event which is triggered before a popup becomes visible. The event passed into this method does not contain any mouse event information so there is no way for me to use viewtomodel to find out how to modify the selection. I could use MouseInfo but that seems dubious at best.
- Using MousePressed/MouseReleased events in the JTextPane or JFrame. Apparently, neither of these events are invoked when a popup menu is triggered. In fact, I still can't determine what the parent component of my popup menu is. (I did read that in windows "MouseReleased" is the popup trigger, while in other systems "MousePressed" is the trigger. I tried both and neither worked).
So, I guess the problem is that I can't seem to find a place to put code where it would be called before the popup menu becomes visible, but has awareness of the mouseEvent that triggered the popup menu. I must be missing something here.
with a popup menu that is assigned to the JTextPane through the JTextPane.setComponentPopupMenu method.
You can use the older approach of displaying the popup based on your own custom MouseListener.
See the section from the Swing tutorial on Bringing Up a Popup Menu. Now you have access to the MouseEvent so you can convert that point to a point in the Document so you know where the click was made, on selected or unselected text.
精彩评论