I have element in fxml
and i set method at onKeyPressed
there
<TableView fx:id="topTable" onKeyPressed="#copyToClipboard" prefHeight="200.0" prefWidth="200.0">
but i don't understand how to get KeyCode's from this EventHandler in method.
@FXML
private TableView<ObservableList<String>> topTable;
...
public void copyToClipboard(){
System.out.println(topTable.getOnKeyPressed().toString());
}
With help of this action i would like to copy data from cells of TableColumn
.
Can someone explain me what can i do with Handler from getOnKeyPressed
?
When you add an event handler via FXML the method in the controller can either take no parameters or one parameter with the appropriate event type. In your case, since you're using onKeyPressed
, you can define the controller method like so:
public void copyToClipboard(KeyEvent event) {
if (event.isShortcutDown() && event.getCode() == KeyCode.C) {
Clipboard cp = Clipboard.getSystemClipboard();
// add your data to the clipboard
}
}
For more information:
Clipboard
To know which Event
type the parameter should be, look at the event handler property you're attempting to use. In your question you are setting the onKeyPressed
property via FXML. This property has the following signature:
ObjectProperty<EventHandler<? super KeyEvent>>
The type of Event
the EventHandler
is supposed to handle is stated in the generic type of the EventHandler
; in this case, KeyEvent
.
There are many of these "event handler properties" declared for Node
. Some subclasses will add their own—such as the onAction
property of ButtonBase
(uses an ActionEvent
).
If it helps, you can think of setting event handler properties from FXML as similar to using method references*:
public class Controller {
@FXML private TableView<?> topTable;
@FXML
private void initialize() {
topTable.setOnKeyPressed(this::copyToClipboard);
}
public void copyToClipboard(KeyEvent event) {}
}
* This is not actually the case as what the FXMLLoader
does is more complicated (reflection).