Set the gaps between two components for FlowLayout - Java Swing

Java examples for Swing:FlowLayout

Introduction

To set the gaps between components either in the constructor of FlowLayout or using its setHgap() and setVgap() methods.

Demo Code

import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    int horizontalGap = 20;
    int verticalGap = 10;
    JFrame frame = new JFrame("Flow Layout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container contentPane = frame.getContentPane();
    FlowLayout flowLayout = new FlowLayout(FlowLayout.LEADING, horizontalGap,
        verticalGap);/*  w  w  w.j  ava 2s .  co m*/
    contentPane.setLayout(flowLayout);
    frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    for (int i = 1; i <= 3; i++) {
      contentPane.add(new JButton("Button " + i));
    }

    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials