基本上我正在尝试在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.
更多推荐
发布评论