How to Disable a Button After It's Clicked in JavaFX 


               


How to Disable a Button After It's Clicked in JavaFX

Java


In this article, we show how to disable a button after it's clicked in JavaFX.

After we've created the button, we can use the following code to disable the button once the user has clicked it.



Basically you just have to insert this statement into the code once the submit button has been clicked. After this, the button becomes disabled.

So we put this code into the code that handles the click event of the button.

The full Java code that disables a button after the button is clicked is shown below.



So just like any JavaFX program, we import all the packages we need to run our code.

We create our public class that extends the Application class, so that we inherit all of the code (classes, methods, etc.) in the Application class.

We override the start() method, which is found in the Application class.

We set the title, create the question by making a label, and create another label that will be used to give output to the user on whether the correct answer was chosen or not.

We then create the button and name it button. We put the text "Submit" on the button.

We then create our radio buttons and link them all to the group question1.

Now we get to the event handler for the button. When the user clicks on the button, the e parameter is triggered, because the clicks represents an event. After this is done, this is where we want to put our code to disable the button.

So in the code that handles the event handler for the button, we disable the button.

This is shown in the code above.

The correct answer to the question, "What is 10 + 20?" is 30, which is radio button 3. Therefore, if radio3 is selected, we output that this is the correct answer. We also then disable the button using the statement, button.setDisable(true);

Since all the other choices are wrong, we have an else statement that states that the answer is wrong. In the same manner, we disable the button using the statement, button.setDisable(true);

And this concludes the code needed to disable a button after it is clicked.

The rest of the code finishes building the window. We create the layout, add all elements to the layout, create the scene, add the scene to the stage, and show the stage.

We then launch the program through the main method.

Running the code above gives us the following shown at the link: JavaFX Disable Button After Click.

And this is all that is required to disable a button after it's clicked.


Related Resources

How to Add a Title to a Window Using JavaFX




HTML Comment Box is loading comments...