I am currently writing an app where the user sometimes needs to wait for longer periods of times. Therefore, i have created a progressbar that shows how far along it is. This seemed to work great at first, but now that i have switched from a commandline app to a GUI, the progressbar does not show any of its components.
I have tried to convert the progressbar from a JFrame to a JDialog, but that didn't make the difference. Since my project is quite big i cannot post all of my code, but here is the ProgressBar.java:
public ProgressBar(String operationName, String operationDescription, int operationsMax) {
this.operationsMax = operationsMax;
this.operationName = operationName;
this.operationDescription = operationDescription;
init();
}
private void init(){
this.progress = 0.0;
TextEditor textEditor = TextEditor.getInstance();
if(textEditor == null) {
this.dialog = new JDialog();
dialog.setTitle(operationName);
} else {
this.dialog = new JDialog(textEditor.getFrame(), operationName);
}
this.panel = new JPanel();
this.progressBar = new JProgressBar((int) progress);
this.label = new JLabel(operationDescription);
progressBar.setPreferredSize(new Dimension(650,60));
progressBar.setStringPainted(true);
label.setFont(new Font("Dialog",Font.BOLD, 20));
label.setLabelFor(progressBar);
panel.add(label);
panel.add(progressBar);
dialog.add(panel);
Image img = new ImageIcon(DocHandler.getInstance().getLogoLocation()).getImage();
dialog.setIconImage(img);
dialog.setSize(700, 190);
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setResizable(false);
dialog.requestFocus();
dialog.setVisible(true);
}
/**
* Sets the progress of the bar to the specified percent level
* @param percent
*/
public void updateProgress(double percent) {
this.progress = percent*100;
int progressInt = (int) progress;
progressBar.setValue(progressInt);
progressBar.setVisible(true);
label.setVisible(true);
System.out.println("WHY NOT SHOWING :((");
dialog.invalidate();
dialog.validate();
dialog.repaint();
}
public void close() {
//removed the sleep statement
dialog.dispose();
}
}
I hope you can help me out with this one :) Here you can find a screenshot of how it looks at first before the main frame is created and how it looks afterwards. https://i.stack.imgur.com/laUxo.png
Edit: I have received some helping saying I should use a SwingWOrker, I have tried this in the specific location:
SwingWorker<NGram,Void> modelCreatorTask
= new SwingWorker<NGram, Void>() {
@Override
protected NGram doInBackground() throws Exception {
NGram model = ModelCreator.createModel(N);
return model;
}
};
modelCreatorTask.execute();
try {
model = modelCreatorTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
System.err.println("Failed to create model.");
System.exit(0);
}
But still the dialog remains empty.