Java Swing How to - Update JFrame when resized








Question

We would like to know how to update JFrame when resized.

Answer

//ww w  . j av  a 2 s . c  om
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main  {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    FieldComponent golfgame = new FieldComponent();
    ((Component) golfgame).setFocusable(true);
    frame.getContentPane().add(golfgame);
    frame.pack();
    frame.setVisible(true);
  }
}
class FieldComponent extends JPanel {
  int width = 1000;
  int height = 800;
  int time;
  public FieldComponent() {
    this.time = 1200;
    this.setPreferredSize(new Dimension(width, height));
  }
  @Override
  protected void paintComponent(Graphics window) {
    super.paintComponent(window);
    Graphics2D twoDGraph = (Graphics2D) window;
    if (time % 2 == 0) {
      twoDGraph.setColor(Color.RED);
    } else {
      twoDGraph.setColor(Color.GREEN);
    }
    twoDGraph.fillOval(100, 100, 600, 600);
    time++;
  }
}