I am relatively new to java and am building a Swing Graphics app. The gui is a JFrame with nested JPanels using a variety of Box layouts. The main drawng algorithm plots geometry in real time (based on user interaction) using a GeneralPath. The app runs continuously(utilizing a Swing Timer) unless the user hits a stop button. The drawing algorithm is in a class called Poly that extends a JComponent. I have tried implementing in 2 different ways.
1. I add an instance of Poly each iteration, which works fine, except that it is really slow, as each JComponent gets added. After a few hundred iterations, the repaint rate is not acceptable.
2. I only instantiate a single Poly object and call some drawing methods. The repaint rate is really fast, but whenever I resize the main application window or change the backgroun of the JPanel, the drawing dissappears. I have removed all paint/paintcomponent methods in all my classes and am using getGraphics() locally in the drawing algoirthm.
This is really, really frustrating and help would be greatly appreciated.
Joined: Jan 14, 2004
The getGraphics method is a one–time deal. It just borrows the current graphics context for query or the occasional use. Once java decides to repaint the component (triggered by minimize/restore, maximize, restore events or after a partial/full covering/uncovering by another window) all is lost.
One solution is keep a reference to the objects you have created for rendering and arrange for the component to re–render them each time java (AWT or Swing) calls for the component to repaint itself.