如何在JavaFX中创建按下运行按钮的按钮类型按钮?(How to create a run

编程入门 行业动态 更新时间:2024-10-17 23:25:34
如何在JavaFX中创建按下运行按钮的按钮类型按钮?(How to create a run-while-button-is-pushed type button in JavaFX? [closed])

基本上我正在尝试在GUI上创建一个按钮,该按钮将在按下时每0.5秒运行一些语句。 目前我已经创建了名为“Next Generation”的实际按钮。

Button nextGenButton = new Button("Next Generation");

这之后我该怎么办? 我假设我必须使用某种类型的事件处理程序?

Essentially I'm trying to create a button on a GUI that will run some statements every 0.5 seconds while it is being pressed down. At the moment I have created the actual button named "Next Generation".

Button nextGenButton = new Button("Next Generation");

How would I proceed after this? I'm assuming I would have to use an event handler of some sorts?

最满意答案

查看setOnMousePressed和setOnMouseReleased 。

你的代码看起来像这样:

final Button btn = new Button("Click me!"); btn.setOnMousePressed((event) -> { /** * Check if this is the first time this handler runs. * - If so, start a timer that runs every 0.5 seconds. * - If not, do nothing. The timer is already running. */ }); btn.setOnMouseReleased((event) -> { //Stop the timer. });

请注意,按下按钮时会反复调用onMousePressed ,因此您必须检查它是否是第一次。

Check out setOnMousePressed and setOnMouseReleased.

Your code would look a little something like this:

final Button btn = new Button("Click me!"); btn.setOnMousePressed((event) -> { /** * Check if this is the first time this handler runs. * - If so, start a timer that runs every 0.5 seconds. * - If not, do nothing. The timer is already running. */ }); btn.setOnMouseReleased((event) -> { //Stop the timer. });

Note that onMousePressed is called repeatedly while the button is pressed, so you do have to check whether it's the first time or not.

更多推荐

本文发布于:2023-07-04 17:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   按下   类型   如何在   run

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!