我的JavaFX应用程序中有一个textArea.setOnDragDropped
方法。
在该函数中,我需要知道CTRL是否关闭。
我不能使用textArea.setOnKeyPressed
方法,因为我注意到它仅在焦点位于文本区域时才检测按键。
如何检查是否在应用程序焦点之外按下了某个键?
用例:我打开Windows资源管理器。在窗口浏览器中按CTRL,然后将文件拖到JavaFX应用程序中的我的文本区域。
public class TestApp extends Application {
final SimpleBooleanProperty isControlDown = new SimpleBooleanProperty(false);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Test CTRL Down");
final TextArea ta = new TextArea();
ta.setOnKeyPressed(e -> {
if (e.isControlDown()) {
System.out.println("Contol is down en property set");
isControlDown.setValue(true);
}
});
ta.setOnKeyReleased(event -> isControlDown.set(false));
ta.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
ta.requestFocus();
event.acceptTransferModes(TransferMode.COPY);
}
});
ta.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
success = true;
final String files =
db.getFiles().stream().map(File::getAbsolutePath).collect(Collectors.joining("\n"));
if(isControlDown.getValue())
{
ta.appendText(files + " with control down\n");
System.out.println("Drop files when contol is down");
} else {
ta.appendText(files + " with NOT control down\n");
System.out.println("Drop files when contol is NOT down");
}
event.setDropCompleted(success);
event.consume();
}
});
ScrollPane root = new ScrollPane();
root.setContent(ta);
primaryStage.setScene(new Scene(root, 600, 600));
primaryStage.show();
}
}