Race Status (?) When Using Swing

I switched from using OpenGL through Penumbra to trying to draw directly on JPanel using its graphics context.

It would be great if I did not encounter some problems ... I will compile my code and ~ 1 time out of 25, the graphic (this is a rectangle for example) draws just fine. Another ~ 24 times, it is not.

Here is my code:

(def main (let [frame (JFrame. "This is a test.") main-panel (JPanel. (GridBagLayout.)) tpan (proxy [JPanel] [] (getPreferredSize [] (Dimension. 600 400)))] (doto frame (set-content-pane (doto main-panel (grid-bag-layout :gridx 0 :gridy 0 tpan :gridx 0 :gridy 1 xy-label))) (pack-frame) (set-visible)) (draw-line tpan Color/RED 250 250 50 50))) 

The draw-line function below:

 (defn draw-line [panel color xywh] (let [graphics (.getGraphics panel)] (doto graphics (.setColor color) (.drawRect xywh)))) 

I have no idea what is going on. At first I thought that these were the links I was working on, but then I pulled them out and still have these problems. I have reset lane and goo / swank and emacs. I am very puzzled.

As usual, any help would be appreciated. Hope this is an answer question! Lately, I seem to be asking the impossible :)

+6
java race-condition clojure swing
source share
2 answers

Make sure you are always on the EDT. If you see your GUI working randomly, which is usually the reason. Racing conditions are crucial for rocking because it is designed completely single-threaded.

What you can try, just see, find any method that interacts with the swing component and print Thread.getCurrentThread (). toString () (or something very close to this).

It should always print the name of the stream, and you will see the letters AWT embedded there somewhere. You can even save this thread, test it with every call to Swing, and claim if it is not the same.

Actually, I donโ€™t know why Sun never created a version of the Debug JDK that would say when such things happened (for example, when some kind of swing thread was called from a non-awt thread ...)

+5
source share

You must override paintComponent in the panel. (Choosing a JPanel is probably not the best - use JComponent and some set-opaque on it.)

Also, I think you should be on AWT EDT.

+4
source share

All Articles