将动作事件处理程序添加到文本字段 java fx
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34752169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add action event handler to text field java fx
提问by coders
I have a Textfield node as such in my java fx code:
我的 java fx 代码中有一个 Textfield 节点:
TextField Name= new TextField();
I understand how to fire code if one clicks on a button by adding an event handler like so:
我了解如何通过添加这样的事件处理程序来单击按钮来触发代码:
Button getName= new Button("Save");
getName.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent args) {
System.out.println("You clicked me!"):
}
});
Could I add the same code to my textFieldnode so when one clicks on the text field, it fires a bunch of code? Or how do you do this?
我可以将相同的代码添加到我的textField节点,以便当单击文本字段时,它会触发一堆代码吗?或者你如何做到这一点?
采纳答案by James_D
To respond to mouse clicks, use setOnMouseClicked
.
要响应鼠标点击,请使用setOnMouseClicked
。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ClickOnTextField extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
textField.setOnMouseClicked(e -> {
System.out.println("Clicked");
});
StackPane root = new StackPane(textField);
Scene scene = new Scene(root, 350, 120);
primaryStage.setScene(scene);;
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
回答by Someone
Try this:
试试这个:
TextField yourTextField = new TextField();
yourTextField.focusedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
{
if (newPropertyValue)
{
System.out.println("Textfield on focus");
}
else
{
System.out.println("Textfield out focus");
}
}
});