Un jPopup para varios controles

Tengo un código como este:

    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();

}
private 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?

preguntado el 08 de enero de 11 a las 21:01

2 Respuestas

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() );

Respondido el 09 de enero de 11 a las 07:01

the Event class has a getSource() method that tells you what component was the cause of the event.

Respondido el 09 de enero de 11 a las 01:01

yes, but the source will be the menu item itself, not the text area. - camickr

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.