Java Swing How to - Leave space with EmptyBorder








Question

We would like to know how to leave space with EmptyBorder.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
/*from w  ww.  j a v a  2 s.c  om*/
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    JPanel bottomPanel = new JPanel();
    bottomPanel.add(new JButton("Bottom Button"));
    bottomPanel.setBorder(BorderFactory.createTitledBorder("Bottom Panel"));

    JPanel centerPanel = new JPanel();
    centerPanel.setBorder(BorderFactory.createTitledBorder("Center Panel"));

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(centerPanel, BorderLayout.CENTER);
    mainPanel.add(bottomPanel, BorderLayout.PAGE_END);

    int eb = 25;
    mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

    mainPanel.setPreferredSize(new Dimension(500, 400));

    JFrame frame = new JFrame("Main");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(mainPanel);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }
}