Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I programmatically click a button in JavaFX from another method?

I have a listener class that is networked into my phone to receive input from an application called TouchOSC. In that class, I can call methods whenever I press a button on my phone. What I need to do is to click a JavaFX button to trigger an event in that method whenever my computer receives the input from my phone. How would I trigger something like that?

like image 349
Dylan Lee Blanchard Avatar asked Mar 30 '15 18:03

Dylan Lee Blanchard


People also ask

How do I program a Button in JavaFX?

You can create a Button by instantiating the javafx. scene. control. Button class of this package and, you can set text to the button using the setText() method.

What's the method used to set a handler for processing a Button clicked action?

Use the setOnAction method of the Button class to define what will happen when a user clicks the button.

Do something when Button is clicked JavaFX?

To make a button do something in JavaFX you need to define the executable code usually by using a convenience method like setOnAction() . Then, when the button is clicked, JavaFX does the heavy lifting of fetching that pre-defined code, and executing it on the JavaFX Application thread.


1 Answers

button.fire()

Invoked when a user gesture indicates that an event for this ButtonBase should occur.

When a button is fired, the button's onAction event handler is invoked.

The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.

Sample Code

Creates a button and automatically fires it four times.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.stream.IntStream;

public class RapidFire extends Application {
    private static int nClicks = 0;

    @Override
    public void start(Stage stage) throws IOException {
        // setup button and action handler.
        Button button = new Button("Click Me!");
        button.setOnAction(event -> {
            nClicks++;
            System.out.println("Clicked " + nClicks + " times.");
        });
        button.setPadding(new Insets(10));
        button.setPrefWidth(100);

        // show the button.
        stage.setScene(new Scene(button));
        stage.show();

        // fire the button a few times in succession.
        IntStream.range(0, 4).forEach(
                i -> button.fire()
        );
    }

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

Output of the sample is:

Clicked 1 times.
Clicked 2 times.
Clicked 3 times.
Clicked 4 times.
like image 105
jewelsea Avatar answered Oct 07 '22 19:10

jewelsea