Reputation: 31
I have a GUI with a JTextField that is supposed to represent a progress bar. Initially I have it set to "0%" and it lies in a horizontal position with plenty of space for text. As the program runs, however, the JTextField refuses to change, even after I use progress.setText(). The strange thing is, when i use progress.getText() it prints exactly what it should. I've tried looking around different areas but most just say to use .revalidate() or .repaint which I have tried, neither work. the relevant code is here:
if(box3.isSelected()){
progress.setText("0%");
int i = 0;
FragChecker fc = new FragChecker();
String[] temp = new String[0];
LexicalizedParser lp = fc.LPReciever(temp);
while(i < tn.sentenceSizeGetter()){
tn.fragChecker((double)i, temp, lp);
setProgress(tn.fragPercentDone((double)i));
i++;
}
}
The tn refers to my Tokenizer class, and tn.sentencesSizeGetter returns the size of an array list. tn.fragPercentDone returns the sentence that was processed divided by the total sentences, times 100. the next bit of relevant code is the setProgress:
public void setProgress(String x){
System.out.println(x);
progress.setText(x + "%");
System.out.println(progress.getText());
}
Upvotes: 0
Views: 742
Reputation: 285415
Yours sounds like a classic Swing threading issue -- that you may be running long running code on the Swing event thread, which prevents the GUI from updating any of its graphics. The solution: do your long running code in a background thread, but then be sure to update your Swing component state on the event thread. A SwingWorker would work well for this.
Something like....
progress.setText("0%");
final FragChecker fc = new FragChecker();
final String[] temp = new String[0];
final LexicalizedParser lp = fc.LPReciever(temp);
new SwingWorker<Void, String>() {
int i = 0;
@Override
protected Void doInBackground() throws Exception {
while (i < tn.sentenceSizeGetter()) {
tn.fragChecker((double) i, temp, lp);
publish(tn.fragPercentDone((double) i));
i++;
}
return null;
}
protected void process(java.util.List<String> chunks) {
for (String chunk : chunks) {
setMyProgress(chunk);
}
};
}.execute();
}
Upvotes: 4