Multiple Windows |
Notes: |
Here is a small program that will create multiple windows
(JFrame's), keep track of how many have been created, and exit the
program when the last one is closed.
The code:
import
javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public static final long serialVersionUID = 3; // ND:
junk
static int windowCount = 0;
static int lastX = 20, lastY = 20, newWindowDelta = 40;
windowCount ++;
setTitle ("ManyWindowsDemoND: " +
windowCount);
setSize (400, 400);
setLocation (lastX +=
newWindowDelta, lastY += newWindowDelta);
new
WindowAdapter () {
public void windowClosing (WindowEvent e) {
windowCount --;
if (windowCount == 0) System.exit (0);
} // end closing event handler method
} // end new
inner adapter
); // end adding method
JButton jbNewWindow = new JButton
("New JFrame");
jbNewWindow.addActionListener (e
-> new ManyWindowsDemoND ());
add (jbNewWindow,
BorderLayout.NORTH);
setVisible (true);
validate ();
new ManyWindowsDemoND ();
public class FrameND extends javax.swing.JFrame {
public static final long serialVersionUID = 892374; // ND: junk
static final int WIDTH = 400, HEIGHT = 200;
static final int DX = 20, DY = 20;
static int windowCount = 0;
static FrameND prev = null;
public FrameND () {
windowCount ++;
setSize (WIDTH, HEIGHT);
if (windowCount == 1) {
setLocationRelativeTo (null);
}
else {
java.awt.Point p = prev.getLocation();
setLocation (p.x + DX, p.y + DY);
} // end creating cascading frames
prev = this;
validate ();
setTitle ("Frame Number: " + windowCount);
setVisible (true);
// setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
addWindowListener (
new java.awt.event.WindowAdapter () {
public void windowClosing (java.awt.event.WindowEvent e) {
windowCount --;
if (windowCount == 0) System.exit (0);
} // end closing event handler method
} // end new inner adapter
); // end adding anonymous inner class listener
} // end no-parameter constructor
public FrameND (String s) {
this ();
setTitle (s);
} // String constructor
public FrameND (String s, int w, int h) {
this (s);
setSize (w, h);
} // end String-int-int constructor
public static void main (String args []) {
new FrameND ();
new FrameND ();
new FrameND ("Setting Size as well", 500, 100);
new FrameND ("Another Frame");
new FrameND ();
System.out.println ("-- bye __");
} // end main
} // end class FrameND