I am writing a program for a Golf Simulator. Up to this point, it essentially works as intended, but the window only updates when I drag to resize it. Why would this be? I have attached the relevant classes below (there are others). Help is greatly appreciated. Updated as MWE. The program should change background colors, but only does this when the window is resized. What follows is the FieldComponent Class, and then the main class.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class FieldComponent extends Canvas {
private BufferedImage back;
private int time;
public FieldComponent() {
setVisible(true);
}
public void update(Graphics window) {
paint(window);
}
public void paint(Graphics window) {
Graphics2D twoDGraph = (Graphics2D) window;
if (back == null) {
back = (BufferedImage) createImage(getWidth(), getHeight());
}
Graphics graphToBack = back.getGraphics();
if(time%2==0){
graphToBack.setColor(Color.RED);
}
else{
graphToBack.setColor(Color.GREEN);
}
graphToBack.fillOval(200, 300, 600, 600);
time++;
twoDGraph.drawImage(back, null, 0, 0);
}
}
And the main class:
import javax.swing.JFrame;
import java.awt.Component;
public class GolfRunner extends JFrame {
private static final int width = 1000;
private static final int height = 800;
public GolfRunner() {
super("Golf Simulator");
setSize(width,height);
FieldComponent golfgame = new FieldComponent();
((Component)golfgame).setFocusable(true);
getContentPane().add(golfgame);
setVisible(true);
}
public static void main(String args[]) {
GolfRunner run = new GolfRunner();
}
}