2014-05-09 58 views
1

我創建了一個textarea,並且想要捕獲用戶的paste操作。當用戶**粘貼**時,我想檢查剪貼板的內容並對粘貼內容做些什麼。textarea的`onPaste`在哪裏?

我無法從TextArea類中找到類似onPaste的方法,我該怎麼辦?

我可以趕上keyPressed事件與onKeyPressed方法,並檢查用戶按下控制 + v,或命令 + v,但我不認爲這是最好的解決辦法。

+1

我從來沒有嘗試過這一點(沒有時間了,但可能會在以後嘗試),但你可以嘗試繼承'TextArea'並覆蓋'paste()'方法。 –

回答

4

TextAreaTextInputControl繼承paste()方法,如果從系統剪貼板粘貼內容,則調用此方法。當粘貼文本時沒有特定的事件觸發,但您可以重寫此方法並定義您自己的行爲。標準行爲是用粘貼的內容調用replaceSelection(...),因此一種方法是從系統剪貼板中檢索內容,根據需要對其進行修改,並將修改後的版本傳遞給方法replaceSelection(...)

一個簡單的例子,無論任何剪貼板上的大寫版本膏:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.TextArea; 
import javafx.scene.input.Clipboard; 
import javafx.scene.layout.BorderPane; 
import javafx.stage.Stage; 


public class Main extends Application { 
    @Override 
    public void start(Stage primaryStage) { 
     BorderPane root = new BorderPane(); 

     TextArea textArea = new TextArea() { 
      @Override 
      public void paste() { 
       Clipboard clipboard = Clipboard.getSystemClipboard(); 
       if (clipboard.hasString()) { 
        replaceSelection(clipboard.getString().toUpperCase()); 
       } 
      } 
     }; 
     root.setCenter(textArea); 
     Scene scene = new Scene(root,400,400); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
}