Tyvain
Tyvain

Reputation: 2760

Vaadin disable button during an action

How can I acheive this in Vaadin.

// inside myButton click event
myButton.setEnabled(false);
doMyActionThatTakeSomeTime();
myButton.setEnabled(true);

Inside the event, the button is never disabled because the UI is not refresh.

What would be the best practice to do this in Vaadin 11 (or 10) ?

Edit SOLUTION - How to make it work with Thread

So far, example with Thread (working):

@Push 
@Route(value = "secured")
public class MainView extends VerticalLayout

[ ... ]

// inside click event
UI ui = UI.getCurrent();
new Thread(() -> {       
    ui.access(() -> {
      goButton.setEnabled(false);
      ui.push();
    });

    doMyActionThatTakeSomeTime();

    ui.access(() -> {
      goButton.setEnabled(true);
      ui.push();
    });
}).start();

Upvotes: 2

Views: 2763

Answers (4)

Sergio Hilerio
Sergio Hilerio

Reputation: 3

For me the simplest way is this:

    Button btnAction = new Button("Action");
    btnAction.setDisableOnClick(true);
    btnAction.addClickListener(e -> {
        try {
            for (int i = 0; i < 900000; i++) {
                System.out.println(i);
            }
        } finally {
            btnAction.setEnabled(true);
        }
    });

Upvotes: 0

Tyvain
Tyvain

Reputation: 2760

A better way of doing it:

UI ui = UI.getCurrent();    
ui.access( () -> { 
    // disable button
    goButton.setEnabled(false);
    ui.push();

    doMyActionThatTakeSomeTime();

    // enable
    goButton.setEnabled(true);
    ui.push();
    }); 

Upvotes: -1

Jouni
Jouni

Reputation: 2918

In Vaadin 8, there’s a Button::setDisableOnClick() method for this exact purpose.

That should probably be reintroduced in the newer versions as well.

Upvotes: 2

ollitietavainen
ollitietavainen

Reputation: 4275

Sounds like the "Asynchronous updates" chapter in the docs explains what you want: https://vaadin.com/docs/v11/flow/advanced/tutorial-push-access.html . Basically: run doMyActionThatTakeSomeTime() in a separate background thread, then re-enable the button once the thread completes and Server Push will make sure the UI state is correctly updated.

This is frequently asked topic, there is also another answer here: How to dismiss Vaadin 8 confirmation dialog while performing lengthy operation Doing asynchronous updates work in Vaadin 8 and Vaadin 10+ in similar manner.

Upvotes: 4

Related Questions