Felix Felix - 1 year ago 64
Java Question

Making a button 'dissapear' when pressed

So I'm trying to make a kind of Wheel of Fortune game or Hangman. I have 33 buttons which represent the alphabet, 1 button = 1 letter. When a user presses one, it has to 'dissapear' (become disable and invisible). I created all the buttons in the SceneBuilder so they are located in the FXML file.

How do I actually do that? I created this method for the first button. But it doesn't work properly, no matter what button I press the first one dissapear. Is there an easier way to do it wIthout writing 33 different methods for each button?

public void letterChosen (ActionEvent evt) {

Answer Source

The Button that was clicked is available as the source of the ActionEvent.

Additionally userData could be attached to the Button, in case you cannot get the necessary information to handle the button click from other properties of the Button:

public void letterChosen(ActionEvent event) {
    Button source = (Button) event.getSource();
    System.out.println("pick: "+source.getUserData());


<Button onAction="#letterChosen" userData="a" text="A"/>
<Button onAction="#letterChosen" userData="b" text="B"/>

Note that it isn't necessary to disable a Node that isn't shown, since a Node that is not visible cannot be interacted with. a disabled Button will appear "faded" by default, but could also be shown differently, e.g. using CSS.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download