progress Bar not working from Jframe in java [duplicate] - java

This question already has answers here:
JProgressBar won't update
(1 answer)
How to return value from SwingWorker class and use in other class and enable MenuItem when process is done?
(1 answer)
Java - global, reusable loading dialog
(2 answers)
Closed 5 years ago.
when I am trying to call method updateProgressBar method when the Jbutton is clicked but the progress is not displayed only the blank dialogue Box appear till the value reached 100%.
following is the method from class ProgressBar which will display Jdialogue box with progress bar.
public void updateProgressBar(int i)
{
pb.setString("Processing " + i + "%");
pb.setValue(i);
try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
}
following is how it is called from Jframe.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ProgressBar pd=new ProgressBar();
int i=1,j=100;
pd.setVisible(true);
while (i<=50)
{
pd.updateProgressBar(i);
i++;
}
pd.dispose();
}

Related

JFrame/JDialog shows no content [duplicate]

This question already has answers here:
java thread.sleep puts swing ui to sleep too
(3 answers)
Blank Java Swing Frame
(1 answer)
How to run method with JProgressBar
(1 answer)
Issues with SwingWorker and JProgressBar
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
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.

Starting/Stopping while loop with JButton [duplicate]

This question already has answers here:
Calling a method from a JButton is freezing a JFrame?
(2 answers)
Display indeterminate JProgressBar while batch file runs
(1 answer)
Something seems wrong with the layout, JButton showing unexpected behaviour at resize of the window
(4 answers)
Closed 5 years ago.
I am trying to make a program that has a toggle button (regular JButton) that when clicked, runs a while loop that runs until the button is clicked again to stop it.
I have done this, however, when I click the button, the entire JFrame freezes because of it being stuck in the while loop, as the loop will run forever until the button is pressed again. However, it is impossible to click the button again because the JFrame freezes. The button itself also just stays blue because the JFrame freezes before the colour change occurs; right before I click the button.
My code looks something like this:
boolean isRunning=false;
private void buttonClickEvent(ActionEvent evt) {
if(isRunning){
isRunning=false;
System.out.println("Stopped running!");
jButton.setText("Start Running");
} else { // BELOW IS THE CODE THAT CAUSES IT TO LOCK
isRunning=true;
jButton.setText("Stop Routine");
while(isRunning){
// DO STUFF
}
}
}
EDIT: I tried doing the following code (below) and it does print the text and allow the colour change to occur in the button, but the UI still freezes quickly afterward.
boolean isRunning=false;
private void buttonClickEvent(ActionEvent evt) {
if(isRunning){
isRunning=false;
System.out.println("Stopped running!");
jButton.setText("Start Running");
} else { // BELOW IS THE CODE THAT CAUSES IT TO LOCK
isRunning=true;
jButton.setText("Stop Routine");
new Thread(new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
while(isInRoutine){
System.out.println("lolk");
}
}
});
}
}).start();
}
}

Change jLabel visibility immediately when jButton action performed [duplicate]

This question already has answers here:
Set JLabel Visible when JButton is clicked in actionPerformed
(3 answers)
set text in label during an action event [duplicate]
(2 answers)
Closed 5 years ago.
I am using NetBeans IDE and I have some problem when I am trying to change jLabel visibility to true:
private void buttonActionPerformed(java.awt.event.ActionEvent evt)
{
LoaderLabel.setVisible(true);
try { sleep(1000000); } catch { ... }
}
The visibility is changed only after the long sleep...
The problem is that I want to make some very intensive calculations in this method, but at the same time present some gif.
Why the jLabel visibility is changed only at the end of the function and how do I fix it?
Thanks! :)
This is because you should set the component's properties in EDT thread (Event Dispatch Thread).
Try:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
LoaderLabel.setVisible(true);
}
});
or using Lambda in Java 8
EventQueue.invokeLater(() -> LoaderLabel.setVisible(true));

how to using swingworker to a jprogressbar <update> [duplicate]

This question already has answers here:
Can a progress bar be used in a class outside main?
(3 answers)
Closed 8 years ago.
I have a swingworker that will be representing a jProgressbar. This is the code
private Swingworker timeOfProccess;
class Swingworker extends SwingWorker<Object, Object> {
#Override
protected Object doInBackground() throws Exception {
jProgressBar1.setStringPainted(true);
int progress = 0;
setProgress(0);
while (progress <= 100) {
jProgressBar1.setValue(progress);
Thread.sleep(5);
progress++;
}
mainProccess();
return null;
}
#Override
protected void done() {
jProgressBar1.setValue(100);
JOptionPane.showMessageDialog(null, "Proses Selesai");
jProgressBar1.setValue(0);
jProgressBar1.setStringPainted(false);
}
}
private void btnExecuteActionPerformed(java.awt.event.ActionEvent evt) {
timeOfProccess = new Swingworker();
timeOfProccess.execute();}
I dont know, why the progressbar running is uncontrolled. it is so fast to 100% even the process still working. But void done is success to pop-up the JoptionPane after main process end. where is I am lost in my code. thanks..
Visit How to Use Progress Bars where You will find good examples on progress bar along with detail description.
Don't use Thread.sleep() that sometime hangs the whole swing application instead try with Swing Timer that is most suitable for swing application.
Read more How to Use Swing Timers
sample code:
// delay for 1500 mill-seconds
Timer timer = new javax.swing.Timer(1500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// call for your next task
}
});
timer.setRepeats(true); // you can turn off the repetition
timer.start();
How to get the progressbar showing the number 1 - 100 %.
Use JProgressBar#setStringPainted() method to show the percent done status.

Setting background color to JButton [duplicate]

This question already has an answer here:
Java Swing button colors [duplicate]
(1 answer)
Closed 9 years ago.
I have a question about setting the background color to JButton.
It seems that the this method only changes the color of the border. Here is the difference (left is jButton):
Is there a way to make the background the same?
I'm using setLookAndFeel on Windows 8.
This will work with either the Metal (default) or Windows PLAFs.
import java.awt.Color;
import javax.swing.*;
class ColoredButton {
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JButton b1 = new JButton("Button 1");
b1.setBackground(Color.RED);
// these next two lines do the magic..
b1.setContentAreaFilled(false);
b1.setOpaque(true);
JOptionPane.showMessageDialog(null, b1);
};
SwingUtilities.invokeLater(r);
}
}
Use .setOpaque(true) on the button.

Categories