Really not sure where this fits inrespects to java - could be threads, so I spent some time attempting to learning threads. Kind of given up, as finding a good source that doesn't jump the gun was very hard.
Anyway, I am having problems painting to a JFrame each time I press a JButton. For example:
public int colorValue; .... JButton paintButton = new JButton("Move"); paintButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { while(true) { if (colorValue == 0) colorValue = 1; else colorValue = 0; repaint(); } } } ); .... .... public void paint(Graphics g) { .... if (colorValue == 0) g.setColor(red); else g.setColor(blue); g.fillRect(20,20,50,50); }
What I want is simply a flashing square on the screen. Instead it will turn one colour and stick at it! I can get my desired results, as long as repaint() is called from anywhere apart from inside a SWING component.
I think all this has something to do with threads (ehh).... please someone help. A good solid simple example will help get me unstuck.
Thanks :-)
P.S. First time I have used this code... /code thing, so sorry if the code looks all funny!
Calls to the repaint method get put in a queue and get done when the OS gets around to it. This presents a common and recurring problem in Java. I've always had more problems with it in applets than in applications, but it can show up in either.
One workaround is to use the paintImmediately method that is found is some Swing components. You have to know the dimensions of the area that you want to repaint, which may pose difficulties in some situations.
Another is to force a repaint by changing the visibility of the object. For example, you could have two Panels (or JPanels) - one on top of the other (use OverlayLayout). Draw the rectangle in one color on one and make it visible and the other invisible. Draw in another color on the invisible one, and switch the visibility. Redraw in another color on the first panel, and switch the visibility again. It should appear that the rectangle is changing colors, but you are really changing panels.