Java Swing How to - Maximize JFrame








Question

We would like to know how to maximize JFrame.

Answer

import java.awt.Dimension;
import java.awt.Toolkit;
/*w  w w  . ja v a2s  . c  o m*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setPreferredSize(new Dimension(333, 666));
    add(panel);
    pack();
    if (Toolkit.getDefaultToolkit().isFrameStateSupported(MAXIMIZED_BOTH)) {
      setExtendedState(MAXIMIZED_BOTH);
    } else {
      Dimension max = Toolkit.getDefaultToolkit().getScreenSize();
      max.height -= 20;
      setSize(max);
      setLocation(0, 20);
    }
    setVisible(true);
  }
  public static void main(String... args) {
    new Main();
  }
}