Search code examples
javaswingjframeremoteobject

java remote function need calling twice


I've created a java code (swing GUI JFrame form) that call another class function (which is in another project) when the button is pressed, but it needs me to click the button twice in order to successfully return the value from the called function. Is there any solution?

here is my code,

The GUI

package aarib;

import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import AlKhalil.ui.Aarib;

public class GUI extends javax.swing.JFrame {

    public String Input;
    public String Lexems;
    public Aarib A;

public GUI() {
        initComponents();
        A = new Aarib();
        jTextField1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        jLabel2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        if(jTextField1.getText().isEmpty())
        {
            jLabel2.setText("No input");
        }
        else{
            Input = jTextField1.getText().toString();
            A.inputText= Input;
            try { 

                Lexems = A.LexicalAnalysis();
                jLabel2.setText(Lexems);

            } catch (Exception ex) {
                jLabel2.setText("Error");
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}  

and the remote function

package AlKhalil.ui;
import java.util.*;
import java.util.List;
import AlKhalil.token.*;
import AlKhalil.analyse.*;
import AlKhalil.*;
import AlKhalil.result.*;


public class Aarib {

    public Analyzer analyzer;
    public String myResult="";
    public String inputText="";

    public Aarib() {
        Settings settings = new Settings();
        analyzer = new Analyzer();

    }

    public String LexicalAnalysis() throws Exception {

        Thread t = new Thread() 
        {
            public void run() 
            {
            //some code
                    ...
                    ...
                    ...
            }
        };

       t.start();
       return myResult;
    }
}

Thanks in advance :)


Solution

  • The solution is to wait for the result produced in the Thread t. With your current code you start a concurrent thread and instantly return the attribute myResult. With the second click on your button the myResult is (most times) filled by the thread and returned after starting another concurrent thread doing the calculation.

    I suggest considering some kind of Observer-Pattern for your program. Your GUI then should obsever the calculating thread and get notified about a result, which then will be handled.

    But as we all cannot see the code executed in the thread and as you wait for the thread to finish, why not simply not use a thread.