У меня есть несколько задач, и их свойство progressProperty всегда -1. Исходя из моего опыта, -1 обычно что-то означает, но я не смог найти об этом в документации. Кто-нибудь знает что это значит? или это просто ошибка в том, как я выставляю прогресс?
Чтобы этот вопрос больше касался моей личной проблемы, вы должны знать, что я комбинирую progressProperty нескольких задач и привязываю это к полосе выполнения с помощью doubleBinding. В соответствии с просьбой, вот некоторый код, чтобы свести его к минимуму, я удалил такие вещи, как объявления импорта, основной метод и пометил важные части.
public class X extends Application implements EventHandler<ActionEvent> {
private Task<Void> taskRun;
private Y y;
private ExecutorService exec; // <-- Executor Service
private Stage dialog;
private Stage window;
//Interface inter;
Scene scene;
private ProgressBar progress; // <-- Progress Bar
@Override
public void start(Stage primaryStage) {
y = new Y();
window = primaryStage;
exec = Executors.newCachedThreadPool(); // <-- Executor Service
progress = new ProgressBar(0.0); // <-- Progress Bar
VBox vb = new VBox();
vb.getChildren().add(progress);
scene = new Scene(vb);
window.setScene(scene);
window.show();
run();
}
private DoubleBinding progressBinding = null; // <-- Double binding
private void run() {
taskRun = new Task<Void>() {
@Override
public void run() {
try {
ConverterManager();
} catch (InterruptedException ex) {
Logger.getLogger(X.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected Void call() throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
};
// I need to use the progressProperty of this task first
progressBinding = taskRun.progressProperty().multiply(1);
// Binding doubleBinding to progressBar
progress.progressProperty().bind(progressBinding);
exec.execute(taskRun);
}
private void ConverterManager() throws InterruptedException {
progressBinding = null; // <-- Reset doubleBinding
int anz = 5;
for (int i = 0; i < anz; i++) {
Task<Void> mt = new Task<Void>() {
@Override
public void run() {
try {
// I use another class and have to update
// progress there, I do so with a BiConsumer
y.setProgressUpdate(this::updateProgress);
// Here I call a Method from the other class
// the String parameter is, because I use
// a reflection there
y.startZ("Z");
} catch (Exception ex) {
Logger.getLogger(X.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected Void call() throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
};
// Here I combine the progress of the different ProgressProperties
// Also, I notized that mt.ProgressProperty.get() is -1 for all tasks
DoubleBinding scaledProgress = mt.progressProperty().divide(anz);
if (progressBinding == null) {
progressBinding = scaledProgress;
} else {
// Adding the scaled down progress of the Task to the
// doubleBinding that is connected to the progressBar
progressBinding = progressBinding.add(scaledProgress);
}
exec.execute(mt);
};
}
@Override
public void handle(ActionEvent event) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Вот класс Y
public class Y {
private BiConsumer<Integer, Integer> progressUpdate;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate;
}
void startZ(String className) throws Exception {
Class cls = Class.forName("stackoverflow." + className);
Object obj = cls.newInstance();
Class[] noParams = new Class[0];
Class[] progressParams = new Class[1];
progressParams[0] = BiConsumer.class;
Method bindProgress = cls.getDeclaredMethod("setProgressUpdate", progressParams);
bindProgress.invoke(obj, progressUpdate);
Method method = cls.getDeclaredMethod("start", noParams);
method.invoke(obj);
}
}
А вот и класс Z:
public class Z
{
private BiConsumer<Integer, Integer> progressUpdate;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate ;
}
public void start() {
int gesamt = 1000;
for (int i = 1; i < gesamt; i++) {
if (progressUpdate != null)
progressUpdate.accept(i, gesamt);
}
}
}




Взгляните на java doc
A value of -1 means that the current progress cannot be determined (that is, it is indeterminate). This property may or may not change from its default value of -1 depending on the specific Worker implementation.
Для Progress Bar и Progress Indicator:
Это даст вам пример первой строки (используемые значения: {-1.0f, 0f, 0.6f, 1.0f}):
Java Doc - руководство по пользовательскому интерфейсу
Каким образом вы его связали? Отредактируйте свой пост и поделитесь кодом, без помощи не может быть
Это потому, что я привязываю свой progressBar к своей задаче перед установкой progressProperty? если нет, как я могу это изменить?