Java Swing How to - Handle resize event








Question

We would like to know how to handle resize event.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
//from  w  ww. j  a va2  s.c o  m
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Main {
  public static void main(String[] args) {
    JPanel panel = new JPanel() {
      @Override
      public Dimension getPreferredSize() {
        return new Dimension(200, 200);
      }
    };
    panel.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentResized(ComponentEvent e) {
        System.out.println("Resized to " + e.getComponent().getSize());
      }
      @Override
      public void componentMoved(ComponentEvent e) {
        System.out.println("Moved to " + e.getComponent().getLocation());
      }
    });
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("test", panel);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(tabbedPane);
    frame.pack();
   
    frame.setVisible(true);
  }
}