Marco
Marco

Reputation: 1

How to update java GUI from another Runnable class ? JAVA

I have two classes: - GUI that representing the Interface of my App - RootGraph that is Runnable

I need that a jlabel is visible until the RootGraph is Runnable, when RootGraph finish his job the jlabel have to be set to not visible.

How can I set the state of JLabel in RootGraph, knowing that the running method is not overloadable?

GUI class

RootGraph rg1 =new RootGraph();
            rg1.SetQuery(endpoint,comboNodoGrafoTab1);
            RootGraph rg2 =new RootGraph();
            rg2.SetQuery(endpoint,comboNodoGrafoTab2);

            Thread rt1=new Thread(rg1);
            Thread rt2=new Thread(rg2);

            rt1.start();
            rt2.start();

RootGraph class

public class RootGraph implements Runnable {
private Query_Sparql querysparql;
private JComboBox jc;

public void SetQuery(String endpoint,JComboBox jc)
{
    querysparql=new Query_Sparql();
    querysparql.setEndpoint(endpoint);
    querysparql.addSelect("g",true);
    querysparql.addWhere("GRAPH ?g {?a ?b ?c .}");
    this.jc=jc;
}

@Override
public void run(){


    jc.removeAllItems();
    querysparql.exec();
    Vector<String> ris=querysparql.returnListFromSelect("g");
    jc.addItem("Default Root Graph");
    for(int i=0;i<ris.size();i++)
    {
        jc.addItem(ris.get(i));
        System.out.println(jc.getItemAt(i));
    }
}

Upvotes: 0

Views: 116

Answers (2)

Thirler
Thirler

Reputation: 20760

Note that in Swing you can not invoke methods on GUI classes from other threads unless explicitly stated.

So you have to use (for instance):

SwingUtilities.invokeLater(new Runnable() {
     @Override
     public void run() {
           jc.removeAllItems();
     }
}

If you blindly replace all your swing calls by the above it will probably work (if your threads were threadsafe to begin with), but you will get a messy code. So instead you should collect the data you want to replace your items with, and when done do a single invokeLater() to do all GUI changes.

For more complex interactions, you can resort to Swing worker threads.

Upvotes: 1

AJ.
AJ.

Reputation: 4534

I need that a jlabel is visible until the RootGraph is Runnable, when RootGraph finish his job the jlabel have to be set to not visible.

Simply set JLabel visible property to true before running the RootGraph.

Make JLabel visible property to false as a last statement of the run() method.

Refresh the Frame after run() method.

Upvotes: 0

Related Questions