I'm on Day 2 of using JavaFX, and my teacher is not really helping, so here I am asking for advice. I have this code snippet with two similar lines:
Button button1 = new Button("Click me");
button1.setOnAction(MouseEvent -> {
Backend.reverse_visibility(list);
});
button1.setOnAction(Backend.reverse_visibility(list));
I copied the second line from a YouTube tutorial. I thought the idea was to just call the method when the button is clicked. However, I'm running into an error with line 2:
/home/vncuser/runtime/Main.java:29: error: 'void' type not allowed here
Backend.reverse_visibility(list));
Since `reverse_visibility()` is defined as a void method, it seems there's a mismatch because the documentation states that `setOnAction` requires an EventHandler. Why doesn't line 1 give me the same error? It looks like it should also be problematic since it's not returning anything either. I'm new to this, so I'd love an explanation.
3 Answers
You're spot on about the void type! Basically, line 2 is trying to set the button’s action to the result of your `reverse_visibility`, which is void. But in line 1, you're actually providing a function that will be called when an event occurs.
It's like this: line 1 passes a set of instructions for what to do when the button is pressed, while line 2 tries to hand over nothing, expecting it to work. The button wants to know what to do when clicked, not what to do right now!
A good way to think about it is the concept of event handlers. In your first line, `MouseEvent -> { Backend.reverse_visibility(list); }` defines a handler that JavaFX can call when the button is clicked. The second line is immediately invoking the method instead of merely referencing it. That's why you're running into the void type error. JavaFX is expecting a function to call later, not something that executes now and returns nothing!
The difference comes down to when each line is executed. In the second line, you're calling `Backend.reverse_visibility(list)` right away, which means it runs immediately and tries to set that result (which is void) to the button's action. That’s why you get the error.
In the first line, you’re defining a lambda expression (or an anonymous function) that tells the button to call `reverse_visibility` later, when the button is clicked. It creates a callback that executes your code only on the event, not before. So, while both lines may look similar, line one is setting up future behavior, and line two is trying to execute a method that doesn’t return anything clear for the button's action.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically