简体   繁体   中英

How to make a button be pressed only once in javafx

So I have a four buttons in the main menu and I want the user to only be able to press one button at a time. The reason for this is because several of my buttons go to another screen. If they press that button more than once then the screen will load twice or nth times and I don' want that. So a cheap fix is setting all the buttons to disabled once the user clicks any of those buttons and then is re enabled once they return to the screen. I could use radio Buttons but then the design of the screen will be ruined. Any ideas?

Here is one simple answer.

isDisabled = new SimpleBooleanProperty();
backToMain.disableProperty().bind(isDisabled);

Then I used

isDisabled.setValue(true); // in my eventhandler method

and it worked.

If anyone has a better answer, please post it.

您可以使用Controls FX的“分段”按钮,并在其上实现便宜的想法。

In my opinion it's simpler. In fact you have:

    @FXML
    private Button btn;

Then, where you want that an event happens and the button freezes itself, you put:

btn.setDisable(true);

And once the event happens, the button freezes .

I am not sure how you are creating new windows, but I use this method to allow only one instance of a window open.

Declare your variable in the class:

private Stage settingsStage = new Stage();

Set up your method:

@FXML // this method opens the settings window
void OpenSettings(ActionEvent event) throws IOException {
    // if the stage is already open, exit the method
    if (settingsStage.isShowing()) {
        return;
    }       
    // set up the source controller for the new window
    // FXMLLoader fxmlLoader = new
    // FXMLLoader(getClass().getResource("Settings.fxml"));
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Login.fxml"));
    // load the controls for the window
    Parent settings = (Parent) fxmlLoader.load();
    // make the window always on top of open windows
    settingsStage.setAlwaysOnTop(true);
    // set the title for the window
    settingsStage.setTitle("Login");
    // set the icon for the window
    settingsStage.getIcons().add(new Image("application/images/Lead.png"));
    // set the scene for the stage
    settingsStage.setScene(new Scene(settings));
    settings.getStylesheets().add(getClass().getResource("login.css").toExternalForm());
    // finally display the window to the user
    settingsStage.show();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM