package examples; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * CS401 Example 34 * * Demonstrates some of the capabilities of the FlowLayout Layout Manager Class. * The FlowLayout manager arranges components in order they are added to the * container from left to right across the space of the container. When there * isn't enough space in the row for the next component, a new line is started. * The excess space in a row can be distributed around the components much like * words on a page: the components can be left justified, right justified, or * centered. * * @author PJ Dillon */ public class ex34 { private Container c; private FlowLayout layout; public ex34() { JFrame window = new JFrame("FlowLayout"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); c = window.getContentPane(); /* * Create the Layout Manager and set it to manage the content pane of our * JFrame */ layout = new FlowLayout(); c.setLayout(layout); JButton left, right, center; left = new JButton("Left"); right = new JButton("Right"); center = new JButton("Center"); /* * Here we're using anonymous inner classes. Recall that ActionListener is * an interface, meaning we can't create instances of it. The code below * automatically creates a new class declared inside the ex34 class that * implements the ActionListener interface. The new class then contains the * methods and instance variables defined inside the braces. An instance of * this class is created here and given to the addActionListener method. * Note that only one instance of this class is ever created, and we're * unable to refer to this class elsewhere. */ left.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { layout.setAlignment(FlowLayout.LEFT); layout.layoutContainer(c); } }); center.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { layout.setAlignment(FlowLayout.CENTER); layout.layoutContainer(c); } }); right.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { layout.setAlignment(FlowLayout.RIGHT); layout.layoutContainer(c); } }); c.add(left); c.add(center); c.add(right); window.setSize(300, 80); window.setVisible(true); } public static void main(String[] args) { new ex34(); } }