1

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);
}
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
  • if you're using Java 8, [why not use a lambda?](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) – Jeeter Aug 10 '16 at 18:00
  • 1
    If you're using <= Java 8, why not use a class that implements `Runnable`? – Jonny Henly Aug 10 '16 at 18:00
  • Possible duplicate of [What's the difference between Void and no parameter?](http://stackoverflow.com/questions/14030337/whats-the-difference-between-void-and-no-parameter) – Jonny Henly Aug 10 '16 at 18:03
  • 1
    From the duplicate I linked -- "Because the `Void` class can not be instantiated, the only value you can pass to a method with a `Void` type parameter, such as `handle(Void e)`, is `null`." – Jonny Henly Aug 10 '16 at 18:11
  • Possible duplicate of [Java Pass Method as Parameter](http://stackoverflow.com/questions/2186931/java-pass-method-as-parameter) – Ali Bdeir Aug 10 '16 at 18:19

1 Answers1

3

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!");
    }
}
...
Jeeter
  • 5,887
  • 6
  • 44
  • 67