Java Swing How to - Layout with default settings from GridBagLayout








Question

We would like to know how to layout with default settings from GridBagLayout.

Answer

import java.awt.GridBagLayout;
/*from   w ww . j  a v a 2 s.  co m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Main {
  JFrame frame = new JFrame("Test");
  JPanel panel = new JPanel();
  JButton subscribe = new JButton("Subscribe");
  JButton unsubscribe = new JButton("Unsubscribe");
  JButton refresh = new JButton("Refresh");
  JButton save = new JButton("Save");

  public Main() {
    panel.setLayout(new GridBagLayout());
    panel.add(subscribe);
    panel.add(unsubscribe);
    panel.add(refresh);
    panel.add(save);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    new Main();
  }
}