Java Многопоточность - PullRequest
       75

Java Многопоточность

0 голосов
/ 24 апреля 2020

Я хотел бы создать JPanel, который сам по себе использует dr aws, используя многопоточность.

Мой класс расширяет JPanel и реализует Runnable, и я хочу нарисовать JPanel не в EDT, потому что прослушиватель, который я установил, замораживает его.

Метод paintComponent() устанавливает переменную в true, если компонент должен быть окрашен.

Метод drawManager() вызывает метод draw() которые рисуют компонент. И установите для переменной значение false, когда метод draw() завершит рисование.

Заранее спасибо за ответ!

Вот обзор моего класса:

public MyClass extends JPanel implements Runnable {

    private boolean isDrawing = false;
    private Graphics2D gg;


    public MyClasse() {
        Thread t = new Thread(this);
        t.start();
    }

    // here is the run() method
    @Override
    public void run() {
        try {
            this.drawManager();
        }
        catch(InterruptedException ex) {
            Logger.getLogger(PanelPlateau.class.getName()).log(Level.SEVERE, null, ex);
        }
    }



    // here the paintComponent that tells me : you should draw if you are not drawing
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
        synchronized(this) {
            if(!this.isDrawing) {
                this.gg = (Graphics2D)g.create();

                this.doDraw();
                this.notify();
            }
        }
    }

    // here the code that draw the JPanel when it needs to be drawn
    private void drawManager() throws InterruptedException {
        while(true) {
            synchronized(this) {
                while(!this.isDrawing) {
                    wait();
                }
            }
            this.draw(this.gg);
            this.gg.dispose();
            this.isDrawing = false;
        }
    }

    // here the code to draw my JPanel
    private void draw(Graphics2D g2d) {
        ...
    }
}
...