开发者

Abstract class with Swing Timer

I have an abstract class as follows:

abstract class Grapher implements Runnable{
  ... member variables...
  Timer timer;
  boolean Done;

   public void run(){
          Done = 开发者_开发百科false;
          timer.start();
          while(!Done){}
   }

   public void Grapher(){ //create graph}
   ...
   }

The idea is that I want to have this abstract thread that creates a graph. I then want to extend this class to provide the implementation of what data that should be plotted on the graph. For example:

class RandomGraph extends Grapher{
   ActionListener taskPerformer;

   public RandomGraph(){
      timer = new Timer(1000, taskPerformer);
        taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               // generate random data and add it to the graph data;
               // if ... Done = true
             }

         };
  }}

This should then plot random data to the graph. The problem I'm having is that I'm getting completely stuck in the while(!done) loop. Putting System.out.printlns inside the actionListener tell me the timer does not seem to be working as nothing appears on the console.

Am I being stupid for using threads at all? I thought it might be a good idea If I want the graph to plot data every few milliseconds.


You're passing null to the Timer constructor — you need to initialize taskPerformer first :-)

To address your bigger question: No, you're not stupid for using threads. However, I question your use of an abstract class at all here. What you really want is an interface Grapher describing an object that draws graphs, then a concrete subclass of Runnable (say, GrapherRunner) that sets up the timer, then delegates to a grapher to do the work.

(In OO-speak, this means using composition rather than inheritance.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜