Java Swing How to - Use EmptyBorders on JPanel in BoxLayout.X_AXIS








Question

We would like to know how to use EmptyBorders on JPanel in BoxLayout.X_AXIS.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
/*from  w w w . j av a2  s .co m*/
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public Main() {
    JFrame frame = new JFrame();
    JPanel container = new JPanel();
    container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
    CustomPanel customPanel1 = new CustomPanel(Color.blue);
    CustomPanel customPanel2 = new CustomPanel(Color.red);
    CustomPanel customPanel3 = new CustomPanel(Color.green);
    container.add(customPanel1);
    container.add(customPanel2);
    container.add(customPanel3);
    frame.getContentPane().add(container);
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    new Main();
  }
}

class CustomPanel extends JPanel {
  BufferedImage image;
  @Override
  public Dimension getMinimumSize() {
    return new Dimension(100, 80);
  }
  @Override
  public Dimension getPreferredSize() {
    return new Dimension(200, 160);
  }
  @Override
  public Dimension getMaximumSize() {
    return new Dimension(400, 320);
  }
  public CustomPanel(Color c) {
    setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createEmptyBorder(10, 10, 10, 10),
        BorderFactory.createLineBorder(Color.black, 1)));

    setBackground(c);
  }
}