Java Swing How to - Leave space between controls inside FlowLayout








Question

We would like to know how to leave space between controls inside FlowLayout.

Answer

import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
//from  ww  w  . j  a  va 2  s  .co m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
  static int verticalGap = 50;
  static int horizontalGap = 30;
  static int width = 800;
  static int height = 800;

  public static void main(String[] args) {
    FlowLayout layout = new FlowLayout(FlowLayout.LEADING, horizontalGap,
        verticalGap);
    JButton button = new JButton("Discard");
    JLabel[] panels = new JLabel[5];

    JFrame frame = new JFrame("Poker");
    frame.setSize(width, height);
    frame.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

    JPanel deckPanel = new JPanel(layout);
    for (int i = 0; i < 5; i++) {
      panels[i] = new JLabel("" + i);
      deckPanel.add(panels[i]);
    }
    frame.getContentPane().add(deckPanel);
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    buttonPanel.add(button);
    frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();

    frame.setVisible(true);
  }
}