Java AWT FlowLayout align right

Introduction

By default, a FlowLayout aligns all components in the center of the container.

You can change the alignment by using its setAlignment() method or passing the alignment in its constructor:

// Set the alignment when you create the layout manager object 
FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT); 

// Set the alignment after you have created the flow layout manager 
flowLayout.setAlignment(FlowLayout.RIGHT); 

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) {
        JFrame frame = new JFrame("Flow Layout Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));

        for (int i = 1; i <= 3; i++) {
            contentPane.add(new JButton("Button " + i));
        }/*from w w  w .ja va2  s  .  c  o  m*/

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



PreviousNext

Related