I made a progressbar and it works perfectly. The only issue is that i want to show the progress percentage. first some background information: Netwerk reads in a large file(=bestand) line by line and everytime it reads a line a counter goes up by 1. So the percentage i want to get is the (counter/1380)*100 with 1380 is the number of lines the scanner reads in. When I run it Netwerk reads in the file while the progressbar is running and the progressbar stops when the scanner is ready (so this works perfectly). But the percentage doesn't upgrade. When I debugged I discovered that updateprogress is called after Netwerk has finished reading and therefore the percentage stays at -100%. Does someone have a solution for this?
我做了一个进度条,它完美无缺。唯一的问题是我想显示进度百分比。首先是一些背景信息:Netwerk逐行读取一个大文件(= bestand),每次读取一行计数器上升1.所以我想得到的百分比是(counter / 1380)* 100,1380是扫描仪读入的行数。当我运行它时,Netwerk在进度条运行时读入文件,当扫描仪准备就绪时进度条停止(因此这很有效)。但百分比不升级。当我调试时,我发现在Netwerk完成读取后调用updateprogress,因此百分比保持在-100%。有人有解决方案吗?
Task<Integer> task = new Task<Integer>() {
@Override
public Integer call() throws Exception {
n = new Netwerk(bestand);
updateProgress(((n.getTeller()/1380)*100), 100);
return null;
}
};
pb = new ProgressBar();
pb.progressProperty().bind(task.progressProperty());
Label lg = new Label();
lg.textProperty().bind(Bindings.format("Even geduld... %.0f%%",
task.progressProperty().multiply(100)));
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
progressStage.close();
SaveStage = new Stage();
//initStage
}
});
new Thread(task).start();
So what happens is that I have a thread with a task in it, the task; 1. makes a Netwerk that reads in the document and increments the counter( i tested the counter and it works) 2. Updateprogress() to update the counter has well
所以会发生的事情是我有一个带有任务的线程,即任务; 1.使一个Netwerk读取文件并递增计数器(我测试了计数器并且它工作)2。Updateprogress()更新计数器很好
then i bind the task to the progressbar and i bind the label with a textProperty. The problem is that the label doesn't update.
然后我将任务绑定到进度条,我将标签绑定到textProperty。问题是标签没有更新。
1 个解决方案
#1
Define a variable as attribute of your class
将变量定义为类的属性
class YourClass {
private volatile int percentage;
Initialize it when you start your ProgressBar
, and assign it inside Task
:
启动ProgressBar时初始化它,并在Task中分配它:
Task task = new Task<Integer>() {
@Override
public Integer call() throws Exception {
n = new Netwerk(bestand);
// assign here the percentage variable
percentage = n.getPercentage();
if (n.getTeller() == 1380) {
return null;
}
return null;
}
#1
Define a variable as attribute of your class
将变量定义为类的属性
class YourClass {
private volatile int percentage;
Initialize it when you start your ProgressBar
, and assign it inside Task
:
启动ProgressBar时初始化它,并在Task中分配它:
Task task = new Task<Integer>() {
@Override
public Integer call() throws Exception {
n = new Netwerk(bestand);
// assign here the percentage variable
percentage = n.getPercentage();
if (n.getTeller() == 1380) {
return null;
}
return null;
}