/* AddComp.java CS 585 example of Timer and dynamically adding and removing components to an application. Uses the Window method pack() to determine preferred size and re-validate layout. Mike Barnes 9/19/03 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class addComp extends JFrame { private static addComp app; private Container contentPane; private JLabel aLabel; private int count, minute; private Timer timer; public static void main(String args[]) { app = new addComp("? ? ?"); app.setBounds(30, 30, 10, 10); app.show (); // need to be able to close the window. app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); } public addComp(String frameTitle) { super(frameTitle); count = 0; minute = 1000; // milliseconds in a 5 seconds timer = new Timer(minute, new TimerListener()); timer.start(); contentPane = getContentPane(); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10)); pack(); } class TimerListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (count < 20) { aLabel = new JLabel(Integer.toString(count)); contentPane.add(aLabel); count++; // if there are five components remove the first component. if (count > 5) contentPane.remove(0); app.pack(); // resizes and re-validates Windows } else timer.stop(); } } }