JProgressBar Doesn't Start Until Try-catch finishes











up vote
4
down vote

favorite












I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.



I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";


System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));



} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});









share|improve this question






















  • Use a SwingWorker.
    – Florent Bayle
    Feb 5 '15 at 14:26















up vote
4
down vote

favorite












I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.



I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";


System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));



} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});









share|improve this question






















  • Use a SwingWorker.
    – Florent Bayle
    Feb 5 '15 at 14:26













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.



I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";


System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));



} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});









share|improve this question













I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.



I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";


System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));



} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});






java api try-catch gson jprogressbar






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 5 '15 at 14:17









Lunatic Fnatic

302212




302212












  • Use a SwingWorker.
    – Florent Bayle
    Feb 5 '15 at 14:26


















  • Use a SwingWorker.
    – Florent Bayle
    Feb 5 '15 at 14:26
















Use a SwingWorker.
– Florent Bayle
Feb 5 '15 at 14:26




Use a SwingWorker.
– Florent Bayle
Feb 5 '15 at 14:26












2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted










Try using swing worker in your method.
Swing Worker



Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:



import javax.swing.SwingUtilities;

/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{

private Object value; // see getValue(), setValue()
private Thread thread;

/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{

private Thread thread;

ThreadVar(Thread t)
{
thread = t;
}

synchronized Thread get()
{
return thread;
}

synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;

/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}

/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}

/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}

/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}

/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}

/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{

public void run()
{
finished();
}
};

Runnable doConstruct = new Runnable()
{

public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}


Then add your logic inside:



SwingWorker worker = new SwingWorker() {
@Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...

return 0;
}
};
worker.start();


So the end resuld should look like this (Note that this is untested code):



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

SwingWorker worker = new SwingWorker() {

@Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";

System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));

} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});





share|improve this answer























  • Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
    – Lunatic Fnatic
    Feb 5 '15 at 14:57












  • Glad to help :)
    – Kiki
    Feb 5 '15 at 20:52










  • Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
    – Alekhya Vemavarapu
    Oct 26 '15 at 6:38


















up vote
3
down vote













Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).



Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).



Read this tutorial: Concurrency in Swing



What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).



Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.






share|improve this answer























  • Thank you, the tutorial helped a lot!
    – Lunatic Fnatic
    Feb 5 '15 at 14:58











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f28346293%2fjprogressbar-doesnt-start-until-try-catch-finishes%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










Try using swing worker in your method.
Swing Worker



Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:



import javax.swing.SwingUtilities;

/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{

private Object value; // see getValue(), setValue()
private Thread thread;

/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{

private Thread thread;

ThreadVar(Thread t)
{
thread = t;
}

synchronized Thread get()
{
return thread;
}

synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;

/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}

/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}

/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}

/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}

/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}

/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{

public void run()
{
finished();
}
};

Runnable doConstruct = new Runnable()
{

public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}


Then add your logic inside:



SwingWorker worker = new SwingWorker() {
@Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...

return 0;
}
};
worker.start();


So the end resuld should look like this (Note that this is untested code):



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

SwingWorker worker = new SwingWorker() {

@Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";

System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));

} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});





share|improve this answer























  • Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
    – Lunatic Fnatic
    Feb 5 '15 at 14:57












  • Glad to help :)
    – Kiki
    Feb 5 '15 at 20:52










  • Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
    – Alekhya Vemavarapu
    Oct 26 '15 at 6:38















up vote
2
down vote



accepted










Try using swing worker in your method.
Swing Worker



Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:



import javax.swing.SwingUtilities;

/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{

private Object value; // see getValue(), setValue()
private Thread thread;

/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{

private Thread thread;

ThreadVar(Thread t)
{
thread = t;
}

synchronized Thread get()
{
return thread;
}

synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;

/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}

/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}

/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}

/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}

/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}

/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{

public void run()
{
finished();
}
};

Runnable doConstruct = new Runnable()
{

public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}


Then add your logic inside:



SwingWorker worker = new SwingWorker() {
@Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...

return 0;
}
};
worker.start();


So the end resuld should look like this (Note that this is untested code):



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

SwingWorker worker = new SwingWorker() {

@Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";

System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));

} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});





share|improve this answer























  • Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
    – Lunatic Fnatic
    Feb 5 '15 at 14:57












  • Glad to help :)
    – Kiki
    Feb 5 '15 at 20:52










  • Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
    – Alekhya Vemavarapu
    Oct 26 '15 at 6:38













up vote
2
down vote



accepted







up vote
2
down vote



accepted






Try using swing worker in your method.
Swing Worker



Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:



import javax.swing.SwingUtilities;

/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{

private Object value; // see getValue(), setValue()
private Thread thread;

/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{

private Thread thread;

ThreadVar(Thread t)
{
thread = t;
}

synchronized Thread get()
{
return thread;
}

synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;

/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}

/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}

/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}

/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}

/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}

/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{

public void run()
{
finished();
}
};

Runnable doConstruct = new Runnable()
{

public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}


Then add your logic inside:



SwingWorker worker = new SwingWorker() {
@Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...

return 0;
}
};
worker.start();


So the end resuld should look like this (Note that this is untested code):



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

SwingWorker worker = new SwingWorker() {

@Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";

System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));

} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});





share|improve this answer














Try using swing worker in your method.
Swing Worker



Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:



import javax.swing.SwingUtilities;

/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{

private Object value; // see getValue(), setValue()
private Thread thread;

/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{

private Thread thread;

ThreadVar(Thread t)
{
thread = t;
}

synchronized Thread get()
{
return thread;
}

synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;

/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}

/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}

/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}

/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}

/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}

/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{

public void run()
{
finished();
}
};

Runnable doConstruct = new Runnable()
{

public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}


Then add your logic inside:



SwingWorker worker = new SwingWorker() {
@Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...

return 0;
}
};
worker.start();


So the end resuld should look like this (Note that this is untested code):



kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

SwingWorker worker = new SwingWorker() {

@Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);

try {

HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{"random":") + "}";

System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("n"+sonuclariYazdir(test,0));

} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});






share|improve this answer














share|improve this answer



share|improve this answer








edited Feb 5 '15 at 14:39

























answered Feb 5 '15 at 14:29









Kiki

1,68842133




1,68842133












  • Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
    – Lunatic Fnatic
    Feb 5 '15 at 14:57












  • Glad to help :)
    – Kiki
    Feb 5 '15 at 20:52










  • Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
    – Alekhya Vemavarapu
    Oct 26 '15 at 6:38


















  • Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
    – Lunatic Fnatic
    Feb 5 '15 at 14:57












  • Glad to help :)
    – Kiki
    Feb 5 '15 at 20:52










  • Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
    – Alekhya Vemavarapu
    Oct 26 '15 at 6:38
















Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
– Lunatic Fnatic
Feb 5 '15 at 14:57






Very clear explanation, thanks! I couldn't put worker.finished(); in my try-catch clause which causes when the operation is being done progress bar still goes on. Do I have to use final worker? Edit*** I simply changed the visibility. :)
– Lunatic Fnatic
Feb 5 '15 at 14:57














Glad to help :)
– Kiki
Feb 5 '15 at 20:52




Glad to help :)
– Kiki
Feb 5 '15 at 20:52












Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
– Alekhya Vemavarapu
Oct 26 '15 at 6:38




Hi, this is a wonderful explanation. May I know how can I update the progressbar with some %. My problem matches the scenario explained in this question.
– Alekhya Vemavarapu
Oct 26 '15 at 6:38












up vote
3
down vote













Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).



Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).



Read this tutorial: Concurrency in Swing



What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).



Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.






share|improve this answer























  • Thank you, the tutorial helped a lot!
    – Lunatic Fnatic
    Feb 5 '15 at 14:58















up vote
3
down vote













Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).



Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).



Read this tutorial: Concurrency in Swing



What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).



Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.






share|improve this answer























  • Thank you, the tutorial helped a lot!
    – Lunatic Fnatic
    Feb 5 '15 at 14:58













up vote
3
down vote










up vote
3
down vote









Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).



Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).



Read this tutorial: Concurrency in Swing



What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).



Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.






share|improve this answer














Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).



Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).



Read this tutorial: Concurrency in Swing



What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).



Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.







share|improve this answer














share|improve this answer



share|improve this answer








edited Feb 5 '15 at 14:34

























answered Feb 5 '15 at 14:23









icza

160k24310353




160k24310353












  • Thank you, the tutorial helped a lot!
    – Lunatic Fnatic
    Feb 5 '15 at 14:58


















  • Thank you, the tutorial helped a lot!
    – Lunatic Fnatic
    Feb 5 '15 at 14:58
















Thank you, the tutorial helped a lot!
– Lunatic Fnatic
Feb 5 '15 at 14:58




Thank you, the tutorial helped a lot!
– Lunatic Fnatic
Feb 5 '15 at 14:58


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f28346293%2fjprogressbar-doesnt-start-until-try-catch-finishes%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Hercules Kyvelos

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud