2010-06-02 64 views
1

這真讓我感到困惑。將文本粘貼到JTextComponent(Java)之後獲取操作

我有一個JTextComponent我已經使用JPopupMenu和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()); 

因爲我已經添加了一個動作監聽器抓住的JTextComponent的文字,我想在一個函數中使用的每個動作。

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

...

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

不過,我可以弄個上唯一的文本是它是之前我砍\粘貼到組件,而不是後面的字符串。

有沒有明顯的解決方案呢?

回答

1

將代碼包裝在SwingUtilities.invokeLater(...)的actionPerformed()方法中,這會將代碼添加到EDT的末尾,以便在剪切/複製/粘貼命令之後執行。

+0

這個伎倆! – 2010-06-02 19:54:35

0

那是因爲你不聽你的文本字段,你聽:-)

菜單把你的文本字段的監聽器,或在你的文本字段的文檔,或者一個FilterDocument,或甚至你自己的文件。

+0

哪種類型的監聽器? – 2010-06-02 19:52:28