Java AWT FlowLayout class

Introduction

FlowLayout is the default layout manager.

Here are the constructors for FlowLayout:

FlowLayout()  
FlowLayout(int how)  
FlowLayout(int how, int horz, int vert) 

Valid values for how are as follows:

FlowLayout.LEFT  
FlowLayout.CENTER  
FlowLayout.RIGHT  
FlowLayout.LEADING  
FlowLayout.TRAILING 

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());

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

        frame.pack();
        frame.setVisible(true);
    }
}
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

class FlowLayoutDemo extends JPanel implements ItemListener {

  String msg = "";
  JCheckBox windows, android, solaris, mac;

  public void init() {
    // set left-aligned flow layout
    setLayout(new FlowLayout(FlowLayout.LEFT));

    windows = new JCheckBox("Windows", null, true);
    android = new JCheckBox("Android");
    solaris = new JCheckBox("Solaris");
    mac = new JCheckBox("Mac OS");

    add(windows);//from ww  w .java  2 s  . c  o m
    add(android);
    add(solaris);
    add(mac);

    // register to receive item events
    windows.addItemListener(this);
    android.addItemListener(this);
    solaris.addItemListener(this);
    mac.addItemListener(this);
  }

  // Repaint when status of a check box changes.
  public void itemStateChanged(ItemEvent ie) {
    String msg = "Current state: ";
    msg = "  Windows: " + windows.isSelected();

    msg = "  Android: " + android.isSelected();

    msg = "  Solaris: " + solaris.isSelected();

    msg = "  Mac: " + mac.isSelected();
    System.out.println(msg);
  }

}

public class Main {
  public static void main(String[] args) {
    FlowLayoutDemo panel = new FlowLayoutDemo();

    JFrame application = new JFrame();

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related