Java Swing How to - Let a Java Swing program layout itself








Question

We would like to know how to let a Java Swing program layout itself.

Answer

/*  ww w .java  2 s. c  o  m*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Main extends JFrame implements ActionListener {
  JTextArea f = new JTextArea("A medium sized text");

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel all = new JPanel();
    JButton button = new JButton("Expand");
    button.addActionListener(this);

    all.add(button);
    all.add(f);
    getContentPane().add(all);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        f.setText(f.getText() + "\n" + f.getText());
        setSize(getPreferredSize());
      }
    });
  }

  public static void main(String[] args) {
    Main lst = new Main();
    lst.setVisible(true);
    lst.pack();
  }
}