Initial commit

parents
Showing with 4754 additions and 0 deletions
No preview for this file type
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.awt.*;
import java.awt.event.*;
/** A program that uses all the standard AWT components */
public class AllComponents extends Frame implements ActionListener {
TextArea textarea; // Events messages will be displayed here.
/** Create the whole GUI, and set up event listeners */
public AllComponents(String title) {
super(title); // set frame title.
// Arrange to detect window close events
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
// Set a default font
this.setFont(new Font("SansSerif", Font.PLAIN, 12));
// Create the menubar. Tell the frame about it.
MenuBar menubar = new MenuBar();
this.setMenuBar(menubar);
// Create the file menu. Add to menubar.
Menu file = new Menu("File");
menubar.add(file);
// Create two items for the file menu, setting their label, shortcut,
// action command and listener. Add them to File menu.
// Note that we use the frame itself as the action listener
MenuItem open = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));
open.setActionCommand("open");
open.addActionListener(this);
file.add(open);
MenuItem quit = new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q));
quit.setActionCommand("quit");
quit.addActionListener(this);
file.add(quit);
// Create Help menu; add an item; add to menubar
// Display the help menu in a special reserved place.
Menu help = new Menu("Help");
menubar.add(help);
menubar.setHelpMenu(help);
// Create and add an item to the Help menu
MenuItem about = new MenuItem("About", new MenuShortcut(KeyEvent.VK_A));
about.setActionCommand("about");
about.addActionListener(this);
help.add(about);
// Now that we've done the menu, we can begin work on the contents of
// the frame. Assign a BorderLayout manager with margins for this frame.
this.setLayout(new BorderLayout(10, 10));
// Create two panels to contain two columns of components. Use our custom
// ColumnLayout layout manager for each. Add them on the west and
// center of the frame's border layout
Panel column1 = new Panel();
column1.setLayout(new ColumnLayout(5, 10, 2, ColumnLayout.LEFT));
this.add(column1, "West");
Panel column2 = new Panel();
column2.setLayout(new ColumnLayout(5, 10, 2, ColumnLayout.LEFT));
this.add(column2, "Center");
// Create a panel to contain the buttons at the bottom of the window
// Give it a FlowLayout layout manager, and add it along the south border
Panel buttonbox = new Panel();
buttonbox.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 10));
this.add(buttonbox, "South");
// Create pushbuttons and add them to the buttonbox
Button okay = new Button("Okay");
Button cancel = new Button("Cancel");
buttonbox.add(okay);
buttonbox.add(cancel);
// Handle events on the buttons
ActionListener buttonlistener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.append("You clicked: " +
((Button)e.getSource()).getLabel() + "\n");
}
};
okay.addActionListener(buttonlistener);
cancel.addActionListener(buttonlistener);
// Now start filling the left column.
// Create a 1-line text field and add to left column, with a label
TextField textfield = new TextField(15);
column1.add(new Label("Name:"));
column1.add(textfield);
// Handle events on the TextField
textfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.append("Your name is: " +
((TextField)e.getSource()).getText() + "\n");
}
});
textfield.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
textarea.append("You have typed: " +
((TextField)e.getSource()).getText() + "\n");
}
});
// Create a dropdown list or option menu of choices
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
column1.add(new Label("Favorite color:"));
column1.add(choice);
// Handle events on this choice
choice.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
textarea.append("Your favorite color is: " + e.getItem() + "\n");
}
});
// Create checkboxes, and group them in a CheckboxGroup to give them
// "radio button" behavior.
CheckboxGroup checkbox_group = new CheckboxGroup();
Checkbox[] checkboxes = new Checkbox[3];
checkboxes[0] = new Checkbox("vanilla", checkbox_group, false);
checkboxes[1] = new Checkbox("chocolate", checkbox_group, true);
checkboxes[2] = new Checkbox("strawberry", checkbox_group, false);
column1.add(new Label("Favorite flavor:"));
for(int i = 0; i < checkboxes.length; i++) column1.add(checkboxes[i]);
// Handle events on the checkboxes
ItemListener checkbox_listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
textarea.append("Your favorite flavor is: " +
((Checkbox)e.getItemSelectable()).getLabel() + "\n");
}
};
for(int i = 0; i < checkboxes.length; i++)
checkboxes[i].addItemListener(checkbox_listener);
// Create a list of choices.
List list = new List(4, true);
list.addItem("Java"); list.addItem("C"); list.addItem("C++");
list.addItem("Smalltalk"); list.addItem("Lisp");
list.addItem("Modula-3"); list.addItem("Forth");
column1.add(new Label("Favorite languages:"));
column1.add(list);
// Handle events on this list
list.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
textarea.append("Your favorite languages are: ");
String[] languages = ((List)e.getItemSelectable()).getSelectedItems();
for(int i = 0; i < languages.length; i++) {
if (i > 0) textarea.append(",");
textarea.append(languages[i]);
}
textarea.append("\n");
}
});
// Create a multi-line text area in column 2
textarea = new TextArea(6, 40);
textarea.setEditable(false);
column2.add(new Label("Messages"));
column2.add(textarea);
// Create a scrollpane that displays portions of a larger component
ScrollPane scrollpane = new ScrollPane();
scrollpane.setSize(300, 150);
column2.add(new Label("Scrolling Window"));
column2.add(scrollpane);
// Create a custom MultiLineLabel with a really big font and make it
// a child of the ScrollPane container
String message =
"/*************************************************\n" +
" * AllComponents.java *\n" +
" * Written by David Flanagan *\n" +
" * Copyright (c) 1997 by O'Reilly & Associates *\n" +
" * *\n" +
" *************************************************/\n";
MultiLineLabel biglabel = new MultiLineLabel(message);
biglabel.setFont(new Font("Monospaced", Font.BOLD + Font.ITALIC, 24));
scrollpane.add(biglabel);
}
/** This is the action listener method that the menu items invoke */
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("quit")) {
YesNoDialog d = new YesNoDialog(this, "Really Quit?",
"Are you sure you want to quit?",
"Yes", "No", null);
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("yes")) System.exit(0);
else textarea.append("Quit not confirmed\n");
}
});
d.show();
}
else if (command.equals("open")) {
FileDialog d = new FileDialog(this, "Open File", FileDialog.LOAD);
d.show(); // display the dialog and block until answered
textarea.append("You selected file: " + d.getFile() + "\n");
d.dispose();
}
else if (command.equals("about")) {
InfoDialog d = new InfoDialog(this, "About",
"This demo was written by David Flanagan\n" +
"Copyright (c) 1997 O'Reilly & Associates");
d.show();
}
}
public static void main(String[] args) {
Frame f = new AllComponents("AWT Demo");
f.pack();
f.show();
}
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
/**
* A class to compute the running average of numbers passed to it
**/
public class Averager {
// Private fields to hold the current state.
private int n = 0;
private double sum = 0.0, sumOfSquares = 0.0;
/**
* This method adds a new datum into the average.
**/
public void addDatum(double x) {
n++;
sum += x;
sumOfSquares += x * x;
}
/** This method returns the average of all numbers passed to addDatum() */
public double getAverage() { return sum / n; }
/** This method returns the standard deviation of the data */
public double getStandardDeviation() {
return Math.sqrt(((sumOfSquares - sum*sum/n)/n));
}
/** This method returns the number of numbers passed to addDatum() */
public double getNum() { return n; }
/** This method returns the sum of all numbers passed to addDatum() */
public double getSum() { return sum; }
/** This method returns the sum of the squares of all numbers. */
public double getSumOfSquares() { return sumOfSquares; }
/** This method resets the Averager object to begin from scratch */
public void reset() { n = 0; sum = 0.0; sumOfSquares = 0.0; }
/**
* This nested class is a simple test program we can use to check that
* our code works okay.
**/
public static class Test {
public static void main(String args[]) {
Averager a = new Averager();
for(int i = 1; i <= 100; i++) a.addDatum(i);
System.out.println("Average: " + a.getAverage());
System.out.println("Standard Deviation: " + a.getStandardDeviation());
System.out.println("N: " + a.getNum());
System.out.println("Sum: " + a.getSum());
System.out.println("Sum of squares: " + a.getSumOfSquares());
}
}
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.rmi.*;
import java.util.Vector;
/**
* This class is a placeholder that simply contains other classes and
* for interfaces remote banking.
**/
public class Bank {
/**
* This is the interface that defines the exported methods of the
* bank server.
**/
public interface RemoteBank extends Remote {
/** Open a new account, with the specified name and password */
public void openAccount(String name, String password)
throws RemoteException, BankingException;
/** Close the named account */
public FunnyMoney closeAccount(String name, String password)
throws RemoteException, BankingException;
/** Deposit money into the named account */
public void deposit(String name, String password, FunnyMoney money)
throws RemoteException, BankingException;
/** Withdraw the specified amount of money from the named account */
public FunnyMoney withdraw(String name, String password, int amount)
throws RemoteException, BankingException;
/** Return the amount of money in the named account */
public int getBalance(String name, String password)
throws RemoteException, BankingException;
/**
* Return a Vector of Strings that list the transaction history
* of the named account
**/
public Vector getTransactionHistory(String name, String password)
throws RemoteException, BankingException;
}
/**
* This simple class represents a monetary amount. This implementation
* is really nothing more than a wrapper around an integer. It is a useful
* to demonstrate that RMI can accept arbitrary non-String objects as
* arguments and return them as values, as long as they are Serializable.
* A more complete implementation of this FunnyMoney class might bear
* a serial number, a digital signature, and other security features to
* ensure that it is unique and non-forgable.
**/
public static class FunnyMoney implements java.io.Serializable {
public int amount;
public FunnyMoney(int amount) { this.amount = amount; }
}
/**
* This is a type of exception used to represent exceptional conditions
* related to banking, such as "Insufficient Funds" and "Invalid Password"
**/
public static class BankingException extends Exception {
public BankingException(String msg) { super(msg); }
}
/**
* This class is a simple stand-alone client program that interacts
* with a RemoteBank server. It invokes different RemoteBank methods
* depending on its command-line arguments, and demonstrates just how
* simple it is to interact with a server using RMI.
**/
public static class Client {
public static void main(String[] args) {
try {
// Set the standard RMI security manager so that we can safely load
// untrusted RemoteBank stub code over the network.
System.setSecurityManager(new RMISecurityManager());
// Figure out what RemoteBank to connect to by reading a system
// property (specified on the command line with a -D option to java)
// or, if it is not defined, use a default URL. Note that by default
// this client tries to connect to a server on the local machine
String url = System.getProperty("bank", "rmi:///FirstRemote");
// Now look up that RemoteBank server using the Naming object, which
// contacts the rmiregistry server. Given the url, this call returns
// a RemoteBank object whose methods may be invoked remotely
RemoteBank bank = (RemoteBank) Naming.lookup(url);
// Convert the user's command to lower case
String cmd = args[0].toLowerCase();
// Now, go test the command against a bunch of possible options
if (cmd.equals("open")) { // Open an account
bank.openAccount(args[1], args[2]);
System.out.println("Account opened.");
}
else if (cmd.equals("close")) { // Close an account
FunnyMoney money = bank.closeAccount(args[1], args[2]);
// Note that FunnyMoney currency is denominated in wooden nickels
System.out.println(money.amount+" wooden nickels returned to you.");
System.out.println("Thanks for banking with us.");
}
else if (cmd.equals("deposit")) { // Deposit money
FunnyMoney money = new FunnyMoney(Integer.parseInt(args[3]));
bank.deposit(args[1], args[2], money);
System.out.println("Deposited " + money.amount + " wooden nickels.");
}
else if (cmd.equals("withdraw")) { // Withdraw money
FunnyMoney money = bank.withdraw(args[1], args[2],
Integer.parseInt(args[3]));
System.out.println("Withdrew " + money.amount + " wooden nickels.");
}
else if (cmd.equals("balance")) { // Check account balance
int amt = bank.getBalance(args[1], args[2]);
System.out.println("You have "+amt+" wooden nickels in the bank.");
}
else if (cmd.equals("history")) { // Get transaction history
Vector transactions = bank.getTransactionHistory(args[1], args[2]);
for(int i = 0; i < transactions.size(); i++)
System.out.println(transactions.elementAt(i));
}
else System.out.println("Unknown command");
}
// Catch and display RMI exceptions
catch (RemoteException e) { System.err.println(e); }
// Catch and display Banking related exceptions
catch (BankingException e) { System.err.println(e.getMessage()); }
// Other exceptions are probably user syntax errors, so show usage.
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java [-Dbank=<url>] Bank$Client " +
"<cmd> <name> <password> [<amount>]");
System.err.println("where cmd is: open, close, deposit, " +
"withdraw, balance, history");
}
}
}
}
<APPLET CODE="BorderLayoutExample.class" WIDTH=350 HEIGHT=200></APPLET>
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.applet.*;
import java.awt.*;
public class BorderLayoutExample extends Applet {
String[] borders = {"North", "East", "South", "West", "Center"};
public void init() {
// Create and specify a BorderLayout layout manager that leaves
// 10 pixels of horizontal and vertical space between components
this.setLayout(new BorderLayout(10, 10));
for(int i = 0; i < 5; i++) {
// Swap the order of these arguments in Java 1.1
this.add(borders[i], new Button(borders[i]));
}
}
}
<APPLET CODE="BouncingCircle.class" WIDTH=300 HEIGHT=300></APPLET>
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.applet.*;
import java.awt.*;
/** An applet that displays a simple animation */
public class BouncingCircle extends Applet implements Animation {
int x = 150, y = 50, r=50; // position and radius of the circle
int dx = 11, dy = 7; // trajectory of circle
/** A timer for animation: call our animate() method ever 100
* milliseconds. Creates a new thread. */
AnimationTimer timer = new AnimationTimer(this, 100);
/** Draw the circle at its current position */
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(x-r, y-r, r*2, r*2);
}
/** Move and bounce the circle and request a redraw.
* The timer calls this method periodically. */
public void animate() {
// Bounce if we've hit an edge.
if ((x - r + dx < 0) || (x + r + dx > bounds().width)) dx = -dx;
if ((y - r + dy < 0) || (y + r + dy > bounds().height)) dy = -dy;
// Move the circle.
x += dx; y += dy;
// Ask the browser to call our paint() method to draw the circle
// at its new position.
repaint();
}
/** Start the timer when the browser starts the applet */
public void start() { timer.start_animation(); }
/** Pause the timer when browser pauses the applet */
public void stop() { timer.pause_animation(); }
}
/** This interface for objects that can be animated by an AnimationTimer */
interface Animation { public void animate(); }
/** The thread class that periodically calls the animate() method */
class AnimationTimer extends Thread {
Animation animation; // The animation object we're serving as timer for
int delay; // How many milliseconds between "animation frames"
public AnimationTimer(Animation animation, int delay) {
this.animation = animation;
this.delay = delay;
}
public void start_animation() {
if (isAlive()) super.resume();
else start();
}
public void pause_animation() { suspend(); }
/** Loop forever, calling animate(), and then pausing the specified time. */
public void run() {
for(;;) {
animation.animate();
try { Thread.sleep(delay); } catch (InterruptedException e) { ; }
}
}
}
<APPLET CODE="CardLayoutExample.class" WIDTH=350 HEIGHT=200></APPLET>
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample extends Applet {
public void init() {
// Create a layout manager, and save a reference to it for future use.
// This CardLayout leaves 10 pixels margins around the component.
final CardLayout cardlayout = new CardLayout(10, 10);
// Specify the layout manager for the applet
this.setLayout(cardlayout);
for(int i = 1; i <= 9; i++) {
Button b = new Button("Button #" + i);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) { // When button is clicked
cardlayout.next(CardLayoutExample.this); // display the next one.
}
};
b.addActionListener(listener);
this.add("Button" + i, b); // Specify a name for each component
}
}
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.awt.*;
import java.awt.event.*;
/**
* This class is a convenient subclass of Frame that knows how to
* handled the WindowClosing event generated when the user requests
* that the window be closed. By default it simply closes itself,
* which makes it useful for things like modeless dialogs that can be
* closed without affecting the rest of the application. Subclasses
* of CloseableFrame can override the windowClosing() method if they
* want to perform additional actions. Applications that use the
* CloseableFrame class for a main window may want to exit when a
* CloseableFrame actually closes. They can do this by overriding
* windowClosed() or by registering a separate WindowListener to
* receive the windowClosed() event.
**/
public class CloseableFrame extends Frame implements WindowListener {
// There are two versions of the constructor. Both register the Frame
// as its own WindowListener object
public CloseableFrame() { this.addWindowListener(this); }
public CloseableFrame(String title) {
super(title);
this.addWindowListener(this);
}
// These are the methods of the WindowListener object. Only
// windowClosing() is implemented
public void windowClosing(WindowEvent e) { this.dispose(); }
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.applet.*;
import java.awt.*;
/**
* A version of the Scribble applet that reads two applet parameters
* to set the foreground and background colors. It also returns
* information about itself when queried.
**/
public class ColorScribble extends Scribble {
// Read in two color parameters and set the colors.
public void init() {
super.init();
Color foreground = getColorParameter("foreground");
Color background = getColorParameter("background");
if (foreground != null) this.setForeground(foreground);
if (background != null) this.setBackground(background);
}
// Read the specified parameter. Interpret it as a hexadecimal
// number of the form RRGGBB and convert it to a color.
protected Color getColorParameter(String name) {
String value = this.getParameter(name);
try { return new Color(Integer.parseInt(value, 16)); }
catch (Exception e) { return null; }
}
// Return information suitable for display in an About dialog box.
public String getAppletInfo() {
return "ColorScribble v. 0.02. Written by David Flanagan.";
}
// Return info about the supported parameters. Web browsers and applet
// viewers should display this information, and may also allow users to
// set the parameter values.
public String[][] getParameterInfo() { return info; }
// Here's the information that getParameterInfo() returns.
// It is an array of arrays of strings describing each parameter.
// Format: parameter name, parameter type, parameter description
private String[][] info = {
{"foreground", "hexadecimal color value", "foreground color"},
{"background", "hexadecimal color value", "background color"}
};
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.awt.*;
/**
* This class subclasses DrawableRect and adds colors to the rectangle it draws
**/
public class ColoredRect extends DrawableRect {
// These are new fields defined by this class.
// x1, y1, x2, and y2 are inherited from our super-superclass, Rect.
protected Color border, fill;
/**
* This constructor uses super() to invoke the superclass constructor, and
* also does some initialization of its own.
**/
public ColoredRect(int x1, int y1, int x2, int y2, Color border, Color fill){
super(x1, y1, x2, y2);
this.border = border;
this.fill = fill;
}
/**
* This method overrides the draw() method of our superclass so that it
* can make use of the colors that have been specified.
**/
public void draw(Graphics g) {
g.setColor(fill);
g.fillRect(x1, y1, x2, y2);
g.setColor(border);
g.drawRect(x1, y1, x2, y2);
}
}
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.awt.*;
/**
* This LayoutManager arranges the components into a column.
* Components are always given their preferred size.
*
* When you create a ColumnLayout, you may specify four values:
* margin_height -- how much space to leave on left and right
* margin_width -- how much space to leave on top and bottom
* spacing -- how much vertical space to leave between items
* alignment -- the horizontal position of the components:
* ColumnLayout.LEFT -- left-justify the components
* ColumnLayout.CENTER -- horizontally center the components
* ColumnLayout.RIGHT -- right-justify the components
*
* You never call the methods of a ColumnLayout object. Just create one
* and make it the layout manager for your container by passing it to
* the addLayout() method of the Container object.
*/
public class ColumnLayout implements LayoutManager2 {
protected int margin_height;
protected int margin_width;
protected int spacing;
protected int alignment;
// Constants for the alignment argument to the constructor.
public static final int LEFT = 0;
public static final int CENTER = 1;
public static final int RIGHT = 2;
/** The constructor. See comment above for meanings of these arguments */
public ColumnLayout(int margin_height, int margin_width,
int spacing, int alignment) {
this.margin_height = margin_height;
this.margin_width = margin_width;
this.spacing = spacing;
this.alignment = alignment;
}
/** A default constructor that creates a ColumnLayout using 5-pixel
* margin width and height, 5-pixel spacing, and left alignment */
public ColumnLayout() { this(5, 5, 5, LEFT); }
/** The method that actually performs the layout. Called by the Container */
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Dimension parent_size = parent.getSize();
Component kid;
int nkids = parent.getComponentCount();
int x0 = insets.left + margin_width;
int x;
int y = insets.top + margin_height;
for(int i = 0; i < nkids; i++) {
kid = parent.getComponent(i);
if (!kid.isVisible()) continue;
Dimension pref = kid.getPreferredSize();
switch(alignment) {
default:
case LEFT: x = x0; break;
case CENTER: x = x0 + (parent_size.width - pref.width)/2; break;
case RIGHT: x = parent_size.width-insets.right-margin_width-pref.width;
break;
}
kid.setBounds(x, y, pref.width, pref.height);
y += pref.height + spacing;
}
}
/** The Container calls this to find out how big the layout should to be */
public Dimension preferredLayoutSize(Container parent) {
return layoutSize(parent, 1);
}
/** The Container calls this to find out how big the layout must be */
public Dimension minimumLayoutSize(Container parent) {
return layoutSize(parent, 2);
}
/** The Container calls this to find out how big the layout can be */
public Dimension maximumLayoutSize(Container parent) {
return layoutSize(parent, 3);
}
protected Dimension layoutSize(Container parent, int sizetype) {
int nkids = parent.getComponentCount();
Dimension size = new Dimension(0,0);
Insets insets = parent.getInsets();
int num_visible_kids = 0;
// Compute maximum width and total height of all visible kids
for(int i = 0; i < nkids; i++) {
Component kid = parent.getComponent(i);
Dimension d;
if (!kid.isVisible()) continue;
num_visible_kids++;