How SwingWork works with EDT? - java

Well, i have the following code bellow that works fine, but i wanna understand how works the threads in this code.
private void jLabelInicioMovimentacaoMouseClicked(
java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jLabelInicioMovimentacaoMouseClicked
jStatusBar1.setWaitState(false);
jStatusBar1.setWaitStartMessage("Pesquisando...");
jStatusBar1.setWaitState(true);
this.sw = new SwingWorker() {
#Override
public Object construct() {
try {
jGDataTextFieldDataInicial
.setValue(retornarPrimeiroDiaMovimentacao());
} catch (Exception e) {
e.printStackTrace();
JGOptionPane.showMessageDialog(FFormMain.this,
"Ocorreu um erro nas bibliotecas",
JGOptionPane.ERROR_MESSAGE);
}
return null;
}
#Override
public void finished() {
jStatusBar1.setWaitStartMessage("Finalizado");
jStatusBar1.setWaitState(false);
}
};
sw.start();
}// GEN-LAST:event_jLabelInicioMovimentacaoMouseClicked
So, my idea is: When I execute the jStatusBar1.setWaitState(false) (first line); this code is executed in EDT (Event Dispatcher Thread) instantly, and the others lines too.
But when I execute this.sw = new SwingWorker()... I am creating a new Thread (outside of EDT), when this "Outside Thread" finish, the method "finished()" is called from EDT and the jStatusBar1 is updated.
My concept is right ?

Related

SwingWorker get not finishing

I have been using quite some SwingWorkers recently, and had some issues so I tried to create an SCSSE, but that apparently doesn't want to work
static SwingWorker worker;
public static void main(String[] args) {
worker = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
return "Hello";
}
protected void done() {
System.out.println("I'm done!");
};
};
System.out.println("working");
try {
System.out.println("result: " + worker.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("working finished");
}
when this is executed, it prints "working" and then the script continues to run indefinitely...
You never start the SwingWorker, so the worker.get() method is blocking while it waits for the worker to complete.
You can verify this by adding:
System.out.println("waiting for result");
System.out.println("result: " + worker.get());
If you want the SwingWorker to execute then you need to invoke:
worker.execute()
after you create the SwingWorker.

SWTException: Invalid thread access

I work on a wizard for creation of a java project and get a invalid thread access exception if I run it in the empty workspace for the first time. I try to implement my wizard similar to JavaProjectWizard, but I don't need the second page, so I try to perform finish from the first page and to initialize the second page in advance:
import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageTwo;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
public class SomeNewWizard
extends Wizard
implements INewWizard {
private SomeWizardPageTwo javaWizardPageTwo;
#Override
public void addPages() {
if (javaWizardPageTwo == null)
someWizardPageTwo = new SomeWizardPageTwo(newSeeAppWizardPageOne);
}
#Override
public boolean performFinish() {
/*line 109*/someWizardPageTwo .createProvisonalProject();
final IWorkspaceRunnable op = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
try {
someWizardPageTwo.performFinish(new SubProgressMonitor(monitor, 1));
}
catch (InterruptedException e) {
throw new OperationCanceledException(e.getMessage());
}
finally {
monitor.done();
}
}
};
try {
rule = null;
Job job = Job.getJobManager().currentJob();
if (job != null)
rule = job.getRule();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
#Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
JavaCore.run(op, rule, monitor);
}
catch (OperationCanceledException e) {
throw new InterruptedException(e.getMessage());
}
catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
getContainer().run(true, true, runnable);
}
catch (InvocationTargetException e) {
handleFinishException(getShell(), e);
return false;
}
catch (InterruptedException e) {
return false;
}
return true;
}
public class SomeWizardPageTwo
extends NewJavaProjectWizardPageTwo
{
private NewJavaProjectWizardPageOne mainPage;
public SomeWizardPageTwo(NewJavaProjectWizardPageOne mainPage)
{
super(mainPage);
this.mainPage = mainPage;
}
#Override
public IProject createProvisonalProject()
{
return super.createProvisonalProject();
}
#Override
protected IWizardContainer getContainer()
{
if (mainPage == null)
return null;
return mainPage.getWizard().getContainer();
}
}
The stacktrace can be found here.
The root of the issue seems that ImageDescriptorRegistry is created from the wrong thread because the corresponding IRunnableWithProgress runs forked. But I wonder why does it work for the normal JavaProjectWizard then? And the main question is: how to make it work for my wizard?
getContainer().run(true, true, runnable); causes the runnable to be executed in a separate thread. The first parameter fork is responsible therefore.
The call to javaWizardPageTwo.performFinish() atempts to access the UI thread and causes the invalid thread access exception.
If you set the fork parameter to false, the code will be executed on the current thread.
Why don't you call javaWizardPageTwo.performFinish() directly?
There is not a bug in Display.checkDevice.
Your call to NewJavaProjectWizardPageTwo.performFinish is running in a background thread, but the code is using ImageDescriptorRegistry which needs to be initialized on the User Interface thread.
This is intermittent because sometimes something else that you do will have already initialized the registry.

how can i return control from java swing frame to normal java code

am developing a java application in which I am using swings to develop GUI screens. i am supposed to run some application files. which I did by connecting to command prompt by using Runtime.exec() method. if my application failes to execute properly then a GUI frame will come up asking weather to run that file again or to skip.
here my problem is when I say run that file again the control should return to the point where the frame is called using ui.setvisible(true);
if not the swing frame what can i use to make my code work
public static boolean runFormat(String format,String buildNumber) throws Exception
{
try{
ProcessExecutor process = new ProcessExecutor();
process.executeCommand(format+"\\Scripts"+File.separator+"Step1.bat"+""+"02_00"+" "+format);
process.waitForCompletion();
File file = new File(format+File.separator+"Results1.log");
BufferedReader read = new BufferedReader (new FileReader(file));
String line;
while((line=read.readLine())!=null)
{
if(line.contains("Successful exit."))
{
return true;
}
}
return false;
}
catch(Exception e)
{
System.out.println("EXCEPTION OCCURED..................");
System.out.println("JTag has failed for "+format);
e.printStackTrace();
}
return true;
}
void run(Set<String> formats)
{
try
{
for(String ar : formats)
{
boolean b =runFormat(ar,"001");
if(b==false)
{
ExampleUi ui = new ExampleUi();
ui.setVisible(true);
}
}
}
catch(Exception e)
{
}
}
Thanks in advance
The short answer is no.
The long answer would involve using a SwingWorker and making the decisions about what to do within it's done method
Take a look at Worker Threads and SwingWorker for more details...
public class ProcessWorker extends SwingWorker<Boolean, Void> {
public Boolean doInBackground() throws Exception {
ProcessBuilder pb = new ProcessBuilder(...);
Process p = pb.start();
// Read the input stream in separate thread...
return p.waitFor() == 0;
}
public void done() {
try {
boolean okay = get();
if (!okay) {
// Re-run....?
}
} catch (Exception exp) {
// Show error message, maybe in a JOptionPane
}
}
}

How can I make the thread sleep for a while and then process all the messages?

I'm writing an Android app that uses two threads. One is UI thread and the other handles server communication. Is it possible for the other thread to wait for a specified amount of time and then process all the messages that have arrived and then wait again?
I need this so that I can collect different data and send it to server in one session.
I've build my thread with HandlerThread but now I'm stuck. Can anyone point me to the right direction?
This is the code I'm using inside the second thread:
public synchronized void waitUntilReady() {
serverHandler = new Handler(getLooper()){
public void handleMessage(Message msg) { // msg queue
switch(msg.what) {
case TEST_MESSAGE:
testMessage(msg);
break;
case UI_MESSAGE:
break;
case SERVER_MESSAGE:
break;
default:
System.out.println(msg.obj != null ? msg.obj.getClass().getName() : "is null");
break;
}
}
};
}
EDIT:
I resolved my issue by going with Thread instead of HandlerThread and using queue.
I'm new to programming so I apologize for any horrenous errors but here's the code I ended up using.
public class ServiceThread extends Thread {
// TODO maybe set the thread priority to background?
static ServiceThread sThread = new ServiceThread(); // service thread instance
private volatile Handler mainHandler;
//
public Thread mainThread;
private boolean OK = true;
public Queue<MessageService> msgQueue;
private ThreadPoolExecutor exec;
private ServiceThread() { }
#Override
public void run() {
synchronized (this){
msgQueue = new ConcurrentLinkedQueue<MessageService>();
notifyAll();
}
mainHandler = new Handler(Looper.getMainLooper());
ThreadPoolExecutor exPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
exec = exPool;
// MAIN LOOP
try {
while(OK) {
getMessagesFromQueue();
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//end of loop
}
public void ProcessMessage(MessageService message) {
System.err.println("ProcessMessage with command: " + message.command);
}
/** Called from the Main thread. Waits until msgQueue is instantiated and then passes the reference
* #return Message Queue
*/
public Queue<MessageService> sendQueue() {
synchronized (this){
while(msgQueue == null) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block -- move the try block!
e.printStackTrace();
}
}
}
return msgQueue;
}
public void setOkFalse () {
if (OK == true)
OK = false;
}
// Message handling methods
/** Priority message from UI thread, processed in another thread ASAP.
* Should be used on commands like getBigPicture or getPics when cached pics are running out
* or upload picture etc.
* #param message - Message should always be MessageService class
* TODO check that it really is.
*/
public void prioTask (MessageService message) {
final MessageService taskMsg = message;
Runnable task = new Runnable() {
#Override
public void run(){
ProcessMessage(taskMsg);
}
};
exec.execute(task);
}
/**
* Gets messages from queue, puts them in the list, saves the number of messages retrieved
* and sends them to MessageService.handler(int commands, list messageList)
* (method parameters may change and probably will =) )
*/
public void getMessagesFromQueue() {
int commands = 0;
ArrayList <MessageService> msgList = new ArrayList <MessageService>();
while(!msgQueue.isEmpty()) {
if(msgQueue.peek() instanceof MessageService) {
//put into list?
msgList.add(msgQueue.remove());
commands++;
} else {
//Wrong type of message
msgQueue.remove();
System.err.println("getMessagesFromQueue: Message not" +
" instanceof MessageService, this shouldn't happen!");
}
}
if (commands > 0) {
HTTPConnection conn;
try {
conn = new HTTPConnection();
MessageService.handleSend(commands, msgList, conn);
conn.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
P.S. This is also my first post here. Should I mark it solved or something? How?

SwingWorker issue, method doInBackground not executed?

Sometimes the doInBackgorund() method of my SwingWorker seems not to be executed, it goes directly to the done() method without saving or printing anything on some of my clients machines, so i suppose it's a random thing , and i can't figure out why. Here 's my code :
public class saveCmdWorker extends SwingWorker<Integer, Integer> {
Order ord;
public saveCmdWorker(Order ord) {
this.ord = ord;
}
#Override
public Integer doInBackground() {
if(999 != ord.getCaissier().getIdCaissier())
saveCmd(ord); // database queries
else
JOptionPane.showMessageDialog(null,"Error",JOptionPane.WARNING_MESSAGE);
if(ord.isIsProd() == false){
try {
// print via serial port
Printer.print(ord, false, Restaurant.numCaisse);
} catch (Exception ex) {
PosO2.errorLogger.log(Level.SEVERE, "Printing error", ex);
}
}
try {
Printer.printFacture(ord, false);
if(btnDuplicata.getForeground() == Color.red)
Printer.printFacture(ord, true);
} catch (Exception ex) {
PosO2.errorLogger.log(Level.SEVERE, "Printing error", ex);
}
return 1;
}
#Override
protected void done() {
try {
btnDuplicata.setForeground(Color.black);
ARendre = 0.0;
ord.clear();
for (int j = 0; j < tab_paiement.size(); j++) {
tab_paiement.get(j).setVisible(true);
}
montantRestant.setBackground(Color.red);
} catch(Exception e) {
PosO2.errorLogger.log(Level.SEVERE, "Refresh Error", e);
}
}
}
I execute this worker via this actionlistener :
ActionListener encaissListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
worker = new saveCmdWorker(cmd);
worker.execute();
}
};
I don't have any logs available so i assume no exception is caught. I saw that a JOptionPane was fired in the doInBackground()(consider as ui modification in an other thread?) but the problem exists when the application doesn't go in the else statement. Can this be the cause of my problems? I don't have this bug on my computer, it just works fine.
As per the SwingWorker documentation (http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#execute()):
SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.
So, it looks like you need to create a new instance of your subclass each time you want to run the execute method properly.

Categories