I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics method. I would like the blue square to flash.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
if(blueSqr){
g.setColor(Color.BLUE);
g.fillRect(10, 10, 10, 10);
}
}
public static void main(String[] args){
createWindow();
theWindow.getContentPane().add(new paintTest());
while(true){
blueSqr = false;
System.out.println("off");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
blueSqr = true;
// Needs something here
System.out.println("on");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public static void createWindow(){
theWindow.setSize(500, 500);
theWindow.setLocationRelativeTo(null);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
Any help would be really good.
Use a Swing
Timer
to callrepaint()
. Also, overridepaintComponent()
in aJPanel
, rather thanpaint()
.Something like this:
There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.
your issues are
1) by calling
Thread.sleep(int)
in the Swing related code, never do that, for delaying in Swing (there are lots of topics about why not use sleep in programing languages ...) use Swing Timer2) your
JPanel
doesn't returns anyXxxSize
3) for Swing use
paintComponent()
, only if you have got really important reasons then use methodpaint()
more about repaint and animating Graphics in the 2D Graphics tutorial4) Swing GUI should be built in the Event Dispatch Thread