Michael
Michael

Reputation: 321

how to run 2 threads in JFrame

Hi i got following problem... I have main jframe started like this:

public static void main (String args[]){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Form3 myF=new Form3();                    
        }
    });
};

in the jframe i have Jpanels. On jpanel i want to start 2nd thread. I tried it like this:

try {
    while (DBAccess.haveResult("ASS"+harnessId)==null&&cancelCycle == 0) {

        thread1.sleep(3*1000);
        System.out.println("+++++++++");
        System.out.println(DBAccess.haveResult("ASS"+harnessId));
        res = DBAccess.haveResult("ASS"+harnessId);

    }

} catch (InterruptedException e) {
    e.printStackTrace();
}

but I am unable to stop that thread and cant even cancel it, because main window stops reacting

to clarify my problem: i have "Test" button on JPanel, which is starting test process. Test process consists of loop whiuch is repeating every 3 seconds, this loop checks database status. Problem is I am unable to stop this loop until the status appears in db (while condition), because window is busy after i click on "test". Even implementing runnable and putting test method into "run()" doesnt worked.

testbutton source code:

if (e.getActionCommand().equals("Test")){
            run();}

run method:

@Override
    public final void run() {
        test();
    }

test method:

Map result_row =  DBAccess.addRow("ASS"+harnessId,htOperList.get(seqNumber-1).getNametestprogram(),"",null);
                if(result_row.containsKey("ADDROW")){System.out.println("Record inserted" );}
                Database db = null;
                Map res = null;                
                try {
                    while (DBAccess.haveResult("ASS"+harnessId)==null&&cancelCycle == 0) {

                        thread1.sleep(3*1000);                        
                        System.out.println(DBAccess.haveResult("ASS"+harnessId));
                        res = DBAccess.haveResult("ASS"+harnessId);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

Upvotes: 1

Views: 791

Answers (1)

kiheru
kiheru

Reputation: 6618

You are blocking the event dispatch thread. Use a SwingWorker for heavy tasks. Put the main DB operation in doInBackround(), and use publish() for the interim results.

If you need to stop it before doInBackround() completes, you can use cancel(). See here for notes about that.

Upvotes: 5

Related Questions