user2079564 user2079564 - 3 months ago 22
Java Question

Possible to transfer void as parameter?

I'm writing a console in Javafx, in this console I'm utilizing hyperlinks. Since hyperlinks can do more than just launch a URL I was wondering if you could pass on a void for them to run.

This is my example of a hyperlink launching a URL:

public void writeHyper(String name, String url) {
Hyperlink link = new Hyperlink(name);
link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
});
t.getChildren().add(link);
}


Is it possible to do something along these lines:

public void writeVoid(String name, Void v) {
Hyperlink link = new Hyperlink(name);
link.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
// runs the void
}
});
t.getChildren().add(link);
}

Answer

If you need a function to run, you can use either a lambda (Java 8+ only) or as @JonnyHenly pointed out, a Runnable. Your code then becomes:

public void writeVoid(String name, Runnable r) {
Hyperlink link = new Hyperlink(name);
link.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent e) {
        r.run(); // runs the void
    }
});
t.getChildren().add(link);

...
writeVoid(name, new Runnable() {
    @Override
    public void run() {
        System.out.println("Running!");
    }
}
...