0

Is it possible to start thread in paintComponent() method ?
I would like that thread to invoke the drawLine() method and count new parameters (points) for this method, and to draw a chart of function in this way.

Here's the code,hoply describe better my purposes:

public class generator2 extends JPanel implements Runnable{

    int fnx, fny, fnx1, fny1;
    Math obMathX, obMathY;
    double amplituda1, czestotl1, faza1, amplituda2, czestotl2, faza2;//parameters of the function
    int n=0;
    Thread genKernel;
    Graphics2D g2D;


    public generator2() {
        amplituda1 = 80;
        czestotl1 = 1;
        faza1 = 0;
        amplituda2 = 80;
        czestotl2 = 1;
        faza2 = 3.14 / 2;
        fnx1 = 0;
        fny1 = 0;
        n=0;

        repaint();
    }

    public void runKernel() {
       if (genKernel==null){
       genKernel=new Thread(this);
       genKernel.start();
   }
   }

   public void stopKernel () {
        if (genKernel!=null){
        genKernel=null;
        }
    }


public void paintComponent(Graphics g) {

            super.paintComponent(g);
            g2D = (Graphics2D) g;
            g2D.setColor(Color.black);
            g2D.setBackground(Color.lightGray);

            runKernel();//starting thread which work on the g2D object - is it correct?
}

    public void run() {

        Thread thisThread = Thread.currentThread();

        while (genKernel == thisThread) {

//generetes new point's data
            fnx = (int) (amplituda1 *
                         obMathX.sin(2 * 3.14 * czestotl1 * n * 0.0001 + faza1));
            fny = (int) (amplituda2 *
                         obMathY.sin(2 * 3.14 * czestotl2 * n * 0.0001 + faza2));
            if (n == 0) {
                fnx1 = fnx;
                fny1 = fny;
            }
            n = n + 1;

            [U]g2D.drawLine((fnx1) + 80, (fny1) + 80, (fnx) + 80, (fny) + 80);[/U]//[U]it doesn't work correctly -why? , whats is wrong with colling drawLine method for g2D object here ? and thread strted in paintComponent() method?  :rolleyes: [/U]
            fnx1 = fnx;
            fny1 = fny;
            if (n == 200000) {
                n = 0;
            }
            try {
                Thread.sleep(1);

            } catch (InterruptedException e) {}
        }
    }


    
}

any ideas or experience ?

2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by server_crash
0

It's possible, but I'm not 100% sure.

I believe you can it's just you must recall the paintComponent() method in the run method:

g2D.drawLine((fnx1) + 80, (fny1) + 80, (fnx) + 80, (fny) + 80);

this.paintComponent(g2D);

Since the paintComponent is expecting a graphics object, i believe you MIGHT run into trouble with passing it a graphics2d object.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.