我有一个带有多个文本框的javafx应用程序,用户可以在其中输入信息。我还有一个内置在应用程序中的键盘,当按下它时,它会将该文本添加到文本框中。
我的问题是,由于我有多个文本框,我不知道该将按钮文本添加到哪个框中。在javafx中,有没有一种方法可以检查用户是否点击了某个文本框,这样我就可以检查哪个文本框被选中并将文本添加到其中?
发布于 2018-06-14 14:30:22
您可以使用活动场景的Scene.focusOwner
属性来获取焦点节点。检查它是否为TextInputControl
,并为所单击的按钮调用适当的方法。请注意,如果某个按钮的focusTraversable
为true
,则单击该按钮可能会移动焦点。(默认情况下是这样的。)
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
final Scene scene = new Scene(grid);
for (int i = 0; i < 4; i++) {
grid.add(new TextField(), 0, i);
final String buttonValue = Character.toString((char) ('a'+i));
Button button = new Button(buttonValue);
button.setFocusTraversable(false); // prevent buttons from stealing focus
button.setOnAction(evt -> {
Node fo = scene.getFocusOwner();
if (fo instanceof TextInputControl) {
((TextInputControl) fo).replaceSelection(buttonValue);
}
});
grid.add(button, 1, i);
}
primaryStage.setScene(scene);
primaryStage.show();
}
发布于 2018-06-14 06:40:28
您应该为每个TextField
的focusProperty
创建一个侦听器并设置一个实例变量。
一旦您有了对当前关注的TextField的全局引用,您就可以对其执行您选择的任何处理。
下面是一个快速演示的应用程序。我已经在代码本身中包含了一些额外的细节:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
// Instance variable to hold the currently-selected TextField
private TextField selectedTextField;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Create TextFields
TextField txt1 = new TextField();
TextField txt2 = new TextField();
TextField txt3 = new TextField();
TextField txt4 = new TextField();
// This method sets the same change listener on each textfield
installListener(txt1, txt2, txt3, txt4);
VBox pane = new VBox(5);
pane.setPadding(new Insets(5));
// Add the TextFields to the layout
pane.getChildren().addAll(
new HBox(5, new Label("Txt1: "), txt1),
new HBox(5, new Label("Txt2: "), txt2),
new HBox(5, new Label("Txt3: "), txt3),
new HBox(5, new Label("Txt4: "), txt4)
);
primaryStage.setScene(new Scene(pane));
primaryStage.show();
}
// Accepts multiple TextFields
private void installListener(TextField... textFields) {
// Install the same listener on all of them
for (TextField textField : textFields) {
textField.focusedProperty().addListener((observableValue, oldValue, newValue) -> {
// Set the selectedTextField to null whenever focus is lost. This accounts for the
// TextField losing focus to another control that is NOT a TextField
selectedTextField = null;
if (newValue) {
// The new textfield is focused, so set the global reference
selectedTextField = textField;
System.out.println("Selected Text: " + selectedTextField.getText());
}
});
}
}
}
https://stackoverflow.com/questions/50847111
复制相似问题