This post includes notes on the related Model View and Observer design principles.
The Observer and Observable are defined in Java SE's package.
* * A strange bug in this code is that when the button is pressed * the requested square is not displayed until after the window has * been manually resized. You can try playing with that, or you can try calling update() and paint() in that order instead of repaint(). Container.add: Note: If a component has been added to a container that has been displayed, validate must be called on that container to display the new component.
* * If after the square is visible, the draw button is pressed a second * time then the square disapears and the window needs to be resized * a second time. JFrame; public class Driver package main; import javax.swing. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.
For example, the collections classes from the original JDK (Vector and Hashtable) are always thread-safe. Because there's a great deal of overhead necessary to build thread-safe artifacts, they tend to be much slower than nonthread-safe alternatives.
This is true of the collections classes (which is why we now have Array List and Hashmap, the nonthread-safe alternatives) and Swing.
This article shows how to build thread-safe GUIs in Swing.
In our introduction to threading with Swing, we said that any updates to the user interface must happen on the event dispatch thread.
so just replace repaint() with validate()Ah, the good think of having the javadoc pop up when you mouseover a method.When it came time to build JFC and Swing, one of the design decisions was that thread safety would be eschewed in favor of speed.This doesn't mean the controls can never be accessed from multiple threads, but the developer is now responsible for adding code to ensure that no ill effects occur.How can we do this if we're no longer in the event dispatch thread?Well, the would be a JLabel or JText Field or something of that ilk— it doesn't matter terribly much.