javafxeventhandler

How to use setOnAction event on javafx


I would like to validate if a textfield is empty or not using javafx.

I am confused of event handlers. I want to confirm : - whether there are many ways to use setOnAction :

submit.setOnAction((new EventHandler<MouseEvent>() { 
     public void handle(MouseEvent event) { 
        System.out.println("Hello World"); 
     } 
    }));

or

submit.setOnAction(e -> handle(e));

what is the difference between these two choices?

I would like to validate textfields in my application.

public class AppGUI extends Application{

public static void main(String[] args)
{
    launch();
}


public void start(Stage topView)
{
    createUI(topView);
}

private void createUI(Stage topView)
{
    TextField name = TextField();
    Button submit = new Button("Submit");
    submit.setOnAction(e -> validate());
}
private boolean validate()
{
   // if textfield is empty, return false. else, return true. 
}

I am lost here. Is it okay if the e in setOnAction is not used in validate? How do I pass the value of textfield to validate()? is making the textfields private variables the only way? (because I have so many text fields I wonder if its a good option). in createUI method, how do i say if validate() returns false, show error message and if true, do something else? Thank you and sorry for bothering


Solution

  • what is the difference between these two choices?

    In second option lambdas are used (appeared since Java 8)

    but then what is the purpose of defining e?

    For a button your method have a signature like this setOnAction(EventHandler<ActionEvent> handler) You should see EventHandler tutorials and an ActionEvent javadoc. For instance, from e you can get the object on which the Event initially occurred this way e.getSource()

    It is ok if you don't use e in validate.

    To pass the value of textfield your method should have signature like this

    boolean validate(String text);
    

    Code example:

    private void createUI(Stage topView){
      TextField name = TextField();
      Button submit = new Button("Submit");
    
      submit.setOnAction(e -> {
          boolean validated = validate(name.getText());
          if(validated) System.out.println("validated"); 
      });
    }
    
    private boolean validate(String text){
      return text != null && !text.isEmpty();
    }