在JavaFx中禁用进度条中的取消按钮

问题描述:

我在javafx中创建了一个进度条。默认取消Button。我只想在我的任务完成时禁用此取消按钮。在JavaFx中禁用进度条中的取消按钮

jobProgressView.setGraphicFactory(task -> { 
    return new Button("save"); 
}); 

没有更多的代码,我只能猜测。即使你添加的代码也不足以从你的实现中知道所有的东西。

因此,此解决方案假定您有一个正在运行的任务并在进度条上显示其进度。这里的任务包装在一个服务中,可以重新启动(也许你还需要这个?)。

import javafx.application.Application; 
import javafx.beans.binding.Bindings; 
import javafx.concurrent.Service; 
import javafx.concurrent.Task; 
import javafx.concurrent.Worker; 
import javafx.event.ActionEvent; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.ProgressBar; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

public class CancelButtonDemo extends Application { 

    Service<Integer> service = new MyService(); 

    @Override 
    public void start(Stage primaryStage) { 

     Button start = new Button(); 
     Button cancel = new Button(); 
     ProgressBar progress = new ProgressBar(0); 

     start.setText("Run Task"); 
     start.setOnAction((ActionEvent event) -> { 
      if (!(service.getState().equals(Worker.State.READY))) { 
       service.reset(); 
      } 
      progress.progressProperty().bind(service.progressProperty()); 
      service.start(); 
     }); 
     start.disableProperty().bind(service.runningProperty()); 

     cancel.setText("Cancel Task"); 
     cancel.setOnAction((ActionEvent event) -> { 
      service.cancel(); 
      progress.progressProperty().unbind(); 
      progress.setProgress(0); 
     }); 
     cancel.disableProperty().bind(Bindings.not(service.runningProperty())); 

     VBox root = new VBox(20); 
     root.setAlignment(Pos.CENTER); 
     root.getChildren().addAll(start, progress, cancel); 
     Scene scene = new Scene(root, 300, 250); 
     primaryStage.setTitle("Cancel Button Demo"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     launch(args); 
    } 

    class MyService extends Service<Integer> { 

     @Override 
     protected Task<Integer> createTask() { 
      return new Task<Integer>() { 

       @Override 
       protected Integer call() throws Exception { 
        int iterations; 
        for (iterations = 0; iterations < 10000000; iterations++) { 
         if (isCancelled()) { 
          updateMessage("Cancelled"); 
          break; 
         } 
         updateMessage("Iteration " + iterations); 
         updateProgress(iterations, 10000000); 
        } 
        return iterations; 
       } 
      }; 
     } 
    } 
} 

上述申请是这样的:

enter image description here

+0

我只想禁用任务完成时取消按钮.. –

+0

我udpated我的答案。 – NwDev

+0

你已经做出了这些按钮。但在我的取消按钮是默认情况下。所以它是有点难以禁用。 –