Java Swing How to - Force JContainer to re-layout itself








Question

We would like to know how to force JContainer to re-layout itself.

Answer

import java.awt.BorderLayout;
import java.awt.Font;
// w ww. j a va 2s. c om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main {
  JFrame frame = new JFrame();
  JScrollPane scrollPane = new JScrollPane();
  JTextArea textArea = new JTextArea(10, 15);
  JButton button = new JButton("change");
  Font newFont = new Font("Courier", Font.PLAIN, 10);

  public Main() {
    textArea.setText("This is just a line of text");
    textArea.setFont(newFont);
    button.addActionListener(e -> {
      textArea.setFont(textArea.getFont().deriveFont(20f));
      frame.pack();
    });
    scrollPane.setViewportView(textArea);
    frame.add(scrollPane);
    frame.add(button, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(100, 100);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    Main fs = new Main();
  }
}