How can we minimize/maximize a JFrame programmatically in Java?


A JFrame class is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. A JFrame contains a window with title, border, (optional) menu bar and user-specific components. By default, we can minimize a JFrame by clicking on minimize button and maximize a JFrame by clicking on maximize button at the top-right position of the screen. We can also do programmatically by using setState(JFrame.ICONIFIED) to minimize a JFrame and setState(JFrame.MAXIMIZED_BOTH) to maximize a JFrame.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameIconifiedTest extends JFrame implements ActionListener {
   private JButton iconifyButton, maximizeButton;
   public JFrameIconifiedTest() {
      setTitle("JFrameIconified Test");
      iconifyButton = new JButton("JFrame Iconified");
      add(iconifyButton, BorderLayout.NORTH);
      iconifyButton.addActionListener(this);
      maximizeButton = new JButton("JFrame Maximized");
      add(maximizeButton, BorderLayout.SOUTH);
      maximizeButton.addActionListener(this);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public void actionPerformed(ActionEvent ae) {
      if(ae.getSource().equals(iconifyButton)) {
         setState(JFrame.ICONIFIED); // To minimize a frame
      } else if(ae.getSource().equals(maximizeButton)) {
         setExtendedState(JFrame.MAXIMIZED_BOTH); // To maximize a frame
      }
   }
   public static void main(String args[]) {
      new JFrameIconifiedTest();
   }
}

Output

In the above program, if we click on "JFrame Iconified" button, the frame is minimized and click on "JFrame Maximized" button, the frame is maximized.

Updated on: 10-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements