One jPopup for several controls
I have code like this:
jTextArea1.add(jPopupMenu1);
jTextArea1.setComponentPopupMenu(jPopupMenu1);
jTextField1.add(jPopupMenu2);
jTextField1.setComponentPopupMenu(jPopupMenu2);
and for menu items I have actions:
private void CopyActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.copy();
}
pr开发者_开发百科ivate void Copy1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.copy();
}
Now I think it would be better to use one popup for all text components, how to pass info about which component was clicked to copy text? Maybe there is some more general solution for such case?
Actions should be created by extending TextAction. The TextAction class has a method that will return the text component that last has focus. This action can then be used on a popup menu or on a menu added to the menu bar. So the basic code to create the menu item would be:
JMenuItem copy = new JMenuItem( new CustomAction() );
However, its even easier than that because the DefaultEditorKit already provides a default copy action so all you need to do is:
JMenuItem copy = new JMenuItem( new DefaultEditorKit.CopyAction() );
the Event class has a getSource() method that tells you what component was the cause of the event.
精彩评论