Search code examples
javajavafxevent-handlinginstance-variables

Best way to handle these events in Java/JavaFX


I am not sure if this is proper or not but I wanted to keep my code clean and decided to create different Classes for handling different events. Up until now, I was only handling static variables. Now I was trying to handle instance variables in the same way but not sure if I can do this.

Is there a way to pass the Rectangle object to my EventHandler or should I simply use Lambda for this case ?

MainClass.java

//Static example
static TextField acTxt = new TextField();
...

acTxt.setText("Aircraft Number");
acTxt.setOnMouseReleased(new ClickAction());

...

//Instance Variable Example
public void printRec(){
    for(int i = 0; i < acArray.get(j).flight_array.size(); i++){
        Rectangle leg_rec = new Rectangle(i*10,i*10,10,15);
        leg_rec.setOnMouseClicked(new ClickAction());
    }
}

...

ClickAction.java Class

import static MainClass.acTxt;

    public class ClickAction implements EventHandler<Event>{

        @Override
        public void handle(Event event) {
            if(event.getSource().equals(acTxt)){
                acTxt.clear();
            }
    }

Solution

  • Don't ever make things static simply to provide access to them. By making a field static you completely change its scope. With the exception of constant fields, static fields are almost always a bad design choice and if you are just beginning with Java my advice is to avoid using static for anything except the main method and genuine constants.

    should I simply use [a] Lambda [expression]

    Why wouldn't you? Just do

    acTxt.setOnMouseReleased(e -> acTxt.clear());
    

    This is less verbose, easier to read and understand (assuming you are familiar with lambda expressions, which doesn't take much practice). The actual behavior is defined right where the control is defined, so you don't have to go digging in a different class to discover what happens when the mouse is released.

    Is there a way to pass the Rectangle object to my EventHandler

    I assume you mean the TextField here...? Yes, of course: if you really want to define the event handler as a stand-alone class, just do as you suggest and pass the text field to it....

    public class ClickAction implements EventHandler<Event>{
    
        private final TextField textField ;
    
        public ClickAction(TextField textField) {
            this.textField = textField ;
        }
    
        @Override
        public void handle(Event event) {
            textField.clear();
        }
    
    }
    

    and then

    acTxt.setText("Aircraft Number");
    Rectangle leg_rect = ... ;
    leg_rect.setOnMouseReleased(new ClickAction(acTxt));