zeraDev
zeraDev

Reputation: 411

Swing Thread Violation

While debugging a strange behaviour in Swing I found this tools: CheckThreadViolationRepaintManager edited version by Alex Ruiz. (You must understand what this class does before answering my Question, thanks)

And i fount a thread violation in my code but i dont understand why because I use SwingUtilities.invokeAndWait() everywhere.

Here is the code that cause threadViolation. Only last line cause the bug:

protected void display() {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            asyncDisplay();
        }
    });
}

private void asyncDisplay(){
   System.out.println("is in edt: " + SwingUtilities.isEventDispatchThread());
    this.printedComponent.setVisible(true);
    this.printedComponent.setOpaque(false);
    this.setVisible(true);
}

And the result:

is in edt:  true
exception: java.lang.Exception
java.lang.Exception
at fr.numvision.common.CheckThreadViolationRepaintManager.checkThreadViolations(CheckThreadViolationRepaintManager.java:31)
at fr.numvision.common.CheckThreadViolationRepaintManager.addDirtyRegion(CheckThreadViolationRepaintManager.java:25)
at javax.swing.JComponent.repaint(JComponent.java:4795)
at java.awt.Component.imageUpdate(Component.java:3516)
at javax.swing.JLabel.imageUpdate(JLabel.java:900)
at sun.awt.image.ImageWatched$WeakLink.newInfo(ImageWatched.java:132)
at sun.awt.image.ImageWatched.newInfo(ImageWatched.java:170)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:533)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:126)
at sun.awt.image.GifImageDecoder.sendPixels(GifImageDecoder.java:447)
at sun.awt.image.GifImageDecoder.parseImage(Native Method)
at sun.awt.image.GifImageDecoder.readImage(GifImageDecoder.java:596)
at sun.awt.image.GifImageDecoder.produceImage(GifImageDecoder.java:212)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)

I really dont understand why this.setVisible(true); cause thread violation (this is a JComponent) while this.printedComponent.setVisible(true); dont.

Thanks,

Upvotes: 0

Views: 688

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

The code which caused the exception is not synchronous with your this.setVisible(true); line. That line just flags the component as needing a repaint, and the actual repaint event comes in later, afer setVisible() has returned. What seems to be going on is that some other code, somehow causally related to the repainting of your component, submits some GUI code to an external thread.

The details of all this are impossible to derive from the amount of code you have posted.

Upvotes: 1

Related Questions