01: package com.clientjava.examples.badswingthread;
02:
03: import javax.swing.*;
04: import java.awt.*;
05: import java.io.ByteArrayOutputStream;
06: import java.io.PrintStream;
07:
08: public class ThreadCheckingRepaintManager extends RepaintManager {
09: private int tabCount = 0;
10: private boolean checkIsShowing = false;
11:
12: public ThreadCheckingRepaintManager() {
13: super ();
14: }
15:
16: public ThreadCheckingRepaintManager(boolean checkIsShowing) {
17: super ();
18: this .checkIsShowing = checkIsShowing;
19: }
20:
21: public synchronized void addInvalidComponent(JComponent jComponent) {
22: checkThread(jComponent);
23: super .addInvalidComponent(jComponent);
24: }
25:
26: private void checkThread(JComponent c) {
27: if (!SwingUtilities.isEventDispatchThread()
28: && checkIsShowing(c)) {
29: System.out.println("----------Wrong Thread START");
30: System.out.println(getStracktraceAsString(new Exception()));
31: dumpComponentTree(c);
32: System.out.println("----------Wrong Thread END");
33: }
34: }
35:
36: private String getStracktraceAsString(Exception e) {
37: ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
38: PrintStream printStream = new PrintStream(byteArrayOutputStream);
39: e.printStackTrace(printStream);
40: printStream.flush();
41: return byteArrayOutputStream.toString();
42: }
43:
44: private boolean checkIsShowing(JComponent c) {
45: if (this .checkIsShowing == false) {
46: return true;
47: } else {
48: return c.isShowing();
49: }
50: }
51:
52: public synchronized void addDirtyRegion(JComponent jComponent,
53: int i, int i1, int i2, int i3) {
54: checkThread(jComponent);
55: super .addDirtyRegion(jComponent, i, i1, i2, i3);
56: }
57:
58: private void dumpComponentTree(Component c) {
59: System.out.println("----------Component Tree");
60: resetTabCount();
61: for (; c != null; c = c.getParent()) {
62: printTabIndent();
63: System.out.println(c);
64: printTabIndent();
65: System.out.println("Showing:" + c.isShowing()
66: + " Visible: " + c.isVisible());
67: incrementTabCount();
68: }
69: }
70:
71: private void resetTabCount() {
72: this .tabCount = 0;
73: }
74:
75: private void incrementTabCount() {
76: this .tabCount++;
77: }
78:
79: private void printTabIndent() {
80: for (int i = 0; i < this .tabCount; i++) {
81: System.out.print("\t");
82: }
83: }
84: }
|