Java AWT FlowLayout set alignment

Description

Java AWT FlowLayout set alignment

// FlowLayout allows components to flow over multiple lines.
import java.awt.Container;
import java.awt.FlowLayout;

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

public class Main extends JFrame {
  private final JButton leftJButton = new JButton("Left");
  private final JButton centerJButton = new JButton("Center");
  private final JButton rightJButton = new JButton("Right");
  private final FlowLayout  layout = new FlowLayout();
  private final Container container;

  // set up GUI and register button listeners
  public Main() {
    super("FlowLayout Demo");
    container = getContentPane(); // get container to layout
    setLayout(layout);//from  w  ww  . j a v  a2  s.  c  o  m

    add(leftJButton); // add Left button to frame
    leftJButton.addActionListener(e->{
        layout.setAlignment(FlowLayout.LEFT);
        // realign attached components
        layout.layoutContainer(container);
    });

    // set up centerJButton and register listener
    add(centerJButton); // add Center button to frame
    centerJButton.addActionListener(e->{
        layout.setAlignment(FlowLayout.CENTER);
        // realign attached components
        layout.layoutContainer(container);
    });

    // set up rightJButton and register listener

    add(rightJButton); // add Right button to frame
    rightJButton.addActionListener(e->{
        layout.setAlignment(FlowLayout.RIGHT);
        // realign attached components
        layout.layoutContainer(container);
    });
  } // end Main constructor

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(300, 75);
    Main.setVisible(true);
  }
}



PreviousNext

Related