Viktor Sehr
Viktor Sehr

Reputation: 13099

Getting an action after text is pasted into a JTextComponent (Java)

This really puzzles me.

I have a JTextComponent for which I've added a right-click cut\copy\paste menu using a JPopupMenu and DefaultEditorKit.Cut\Copy\PasteAction().

JMenuItem cutItem = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem copyItem = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem pasteItem = new JMenuItem(new DefaultEditorKit.PasteAction());

For each action I've added an action listener which grabs the JTextComponent's text, which I want to use in a function.

final ActionListener textFieldListener = new ActionListener() {
@Override public void actionPerformed(ActionEvent e){someGlobalFunction(textComponent.getText());
}
}; 

...

cutItem.addActionListener(textFieldListener );
copyItem.addActionListener(textFieldListener );
pasteItem.addActionListener(textFieldListener );

However, the only text I can get hold on is the String which it was before I cut\paste into the component, not after.

Is there any obvious solution for this?

Upvotes: 1

Views: 461

Answers (2)

camickr
camickr

Reputation: 324108

Wrap the code in the actionPerformed() method in a SwingUtilities.invokeLater(...), This will add the code to then end of the EDT so it should execute after the cut/copy/paste commands.

Upvotes: 1

Istao
Istao

Reputation: 7585

It is because you don't listen your text field, you listen the menu :-)

Put a listener on your text field, or on the document of your text field, or perhaps a FilterDocument, or even your own document.

Upvotes: 0

Related Questions