package view; import java.awt.*; // to use Container. import java.awt.event.*; // to use WindowAdpater and WindowEvent. import javax.swing.*; // to use JFrame. /** * A subclass of AFrame containing two JButtons that have event handler called * "commands" to dynamically switch layout managers when the buttons are clicked * upon. * @author D.X. Nguyen */ public class Frame2 extends AFrame { public Frame2(String title) { super(title); } protected void initialize() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); JButton jb1 = new JButton("Grid Layout"); JButton jb2 = new JButton("Flow Layout"); cp.add(jb1); cp.add(jb2); pack(); /** * Registers an anonymous event handler for the clicking of button jb1. * When jb1 is clicked upon, this event handler will respond by * executing its actionPerformed(...) method. */ jb1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jb1Clicked(e); } }); /** * Same as the above. */ jb2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jb2Clicked(e); } }); } /** * Dynamically changes to a GridLayout with 2 rows and 1 column. */ protected void jb1Clicked(ActionEvent e) { System.out.println("Set GridLayout..."); System.out.println("Action event" + e); getContentPane().setLayout(new GridLayout(2,1)); validate(); // forces this frame to re-layout. } /** * Dynamically changes to FlowLayout. */ protected void jb2Clicked(ActionEvent e) { System.out.println("Set FlowLayout..."); getContentPane().setLayout(new FlowLayout()); validate(); // forces this frame to re-layout. } }