質問

I need to fire an event when the user pastes text into my program, specifically a JTextArea. Is there a system independent method for detecting a paste command? I've been looking around, but can't seem to find a listener for this purpose. I'd settle for a non-system safe workaround, but I was hoping there would be a universal method for this.

役に立ちましたか?

解決

Why listen for "pastes"? Why not simply use a DocumentListener added to the PlainDocument that is the JTextArea's "model"? This will notify you of all changes to the document regardless of source. If you want to prevent modification of the document as you listen then use a DocumentFilter. Regardless, if this is a Swing GUI, you probably shouldn't be using KeyListeners at all.

他のヒント

KeyEvent has a constant value named VK_PASTE which can be used inside of KeyListener#keyPressed(KeyEvent e):

public void keyPressed(KeyEvent e) {
  switch(e.getKeyCode()) {
    case KeyEvent.VK_PASTE:
      // do stuff when a paste occurs
  }
}

There are also VK_CUT and VK_COPY, which might be helpful. All of these should be system independent as well, according to the doc.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top