开发者

Problem running a thread in response to a JButton click

开发者 https://www.devze.com 2023-02-01 00:49 出处:网络
I have made a form which, amongst other things, displays a graph (using jfreechart). The graph plots dynamically generated data. 开发者_运维知识库To generate the data I use a thread, as follows:

I have made a form which, amongst other things, displays a graph (using jfreechart). The graph plots dynamically generated data. 开发者_运维知识库To generate the data I use a thread, as follows:

class Grapher extends JFrame implements Runnable{
       ....
     public void run(){
           Thread thisT = Thread.currentThread();
     while(true){
        try{    
            double a = getRand();
            System.out.println(a);
            Millisecond millisecond = new Millisecond();
            if(a == 100){thisThread.stop();}
            timeseries.add(millisecond, a);
            Thread.sleep(100);
        }catch(InterruptedException e){}
    }

If I Set up my program like this, the graph displays fine within my GUI, but starts immediately.

     Grapher graph = new Grapher();
    MyForm testForm = new MyForm();

    testForm.addGraph(graph);      
    testForm.pack();
    testForm.setVisible(true);
    graph.run();

If I miss out the last line graph.run() and add this to the Jbutton event listener, when I click the button, I can see that the thread runs as I get numbers displaying on the console. However, the graph does not update, and the whole form freezes up.

I'm not sure why this is happening, but I'd imagine it's to do with threads?


new Thread(new Grapher()).start();


You are running the thread on the UI thread.

calling .run() on a runnable does not create a new thread

Look into the SwingWorker for a sulution. http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html and read this toturial http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html


You should not have a "while true" loop in you code. If you want animation of some kind then use a Swing Timer to schedule the animation. The Swing tutorial link to by one of the other answer also has a section on How to Use Timers.

0

精彩评论

暂无评论...
验证码 换一张
取 消