Reputation: 1533
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Pane p = new Pane();
p.setPrefSize(400, 300);
Button btn = new Button("Submit");
btn.relocate(10, 10);
TextField tf = new TextField();
tf.relocate(10, 40);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
text = tf.getText();
System.out.println(text);
}
});
btn.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode().equals(KeyCode.ENTER))
text = tf.getText();
System.out.println(text);
}
});
p.getChildren().addAll(btn,tf);
Scene sc = new Scene(p);
primaryStage.setScene(sc);
primaryStage.show();
}
Here is my code. As you can see i have two EventHandlers. One which check if enter is pressed and the other one which check if button is pressed. My goal is to make one method and whenever one of these two EventHandlers activate it takes input from TextFields.
In this example i have only one TextField but in my application i have plenty of them so if i do the same thing in two EventHandlers i will double my code. I guess there is option to make method which will do that for me.
Upvotes: 0
Views: 48
Reputation: 191983
My goal is to make one method and whenever one of these two EventHandlers activate it takes input from TextFields.
In this example i have only one TextField but in my application i have plenty of them
If the goal is a method, then make a method. If you have many text fields and want to do a similar action for them in any handle method, then use a parameter.
public void printTextField(TextField tf)
{
System.out.println(tf.getText());
}
Anywhere in your code, (e.g. In the event handlers) you can now call
printTextField(tf);
Upvotes: 1