我将如何通过另一种方法以编程方式单击 JavaFX 中的按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29353790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would I programmatically click a button in JavaFX from another method?
提问by Dylan Lee Blanchard
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?
我有一个侦听器类,它连接到我的手机中以接收来自名为 TouchOSC 的应用程序的输入。在该课程中,只要按下手机上的按钮,我就可以调用方法。我需要做的是,每当我的计算机从我的手机接收到输入时,单击一个 JavaFX 按钮以在该方法中触发一个事件。我怎么会触发这样的事情?
回答by jewelsea
Invoked when a user gesture indicates that an event for this ButtonBase should occur.
当用户手势指示应发生此 ButtonBase 的事件时调用。
When a button is fired, the button's onAction
event handler is invoked.
当一个按钮被触发时,按钮的onAction
事件处理程序被调用。
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.
按钮的动作,只要按钮被触发就会调用。这可能是由于用户使用鼠标单击按钮、触摸事件或按键,或者开发人员以编程方式调用了 fire() 方法。
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.