# BorderTest.java Five buttons arranged by BorderLayout
BorderLayout divides the window into five regions: NORTH, SOUTH, EAST, WEST, and CENTER.
/./././././././././././././
import java.applet.Applet;
import java.awt.*;
/** An example of BorderLayout.
*
&&&&&&&&&&&&&&&&&&&&&&&&&&&
public class BorderTest extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("Button 1"), BorderLayout.NORTH);
add(new Button("Button 2"), BorderLayout.SOUTH);
add(new Button("Button 3"), BorderLayout.EAST);
add(new Button("Button 4"), BorderLayout.WEST);
add(new Button("Button 5"), BorderLayout.CENTER);
}
}
&&&&&&&&&&&&&&&&&&&&
Aug 26
BorderLayout divides the window into five regions
Aug 26
Checkboxes
Checkboxes.java Inherits from CloseableFrame.java.
******************
import java.awt.*;
/./././././././././
public class Checkboxes extends CloseableFrame {
public static void main(String[] args) {
new Checkboxes();
}
public Checkboxes() {
super("Checkboxes");
setFont(new Font("SansSerif", Font.BOLD, 18));
setLayout(new GridLayout(0, 2));
Checkbox box;
for(int i=0; i<12; i++) {
box = new Checkbox("Checkbox " + i);
if (i%2 == 0) {
box.setState(true);
}
add(box);
}
pack();
setVisible(true);
}
}
Aug 26
Places a Panel holding 100 buttons in a ScrollPane
import java.applet.Applet;
import java.awt.*;
/** Places a Panel holding 100 buttons in a ScrollPane that is
* too small to hold it.
*
*/
public class ScrollPaneTest extends Applet {
public void init() {
setLayout(new BorderLayout());
ScrollPane pane = new ScrollPane();
Panel bigPanel = new Panel();
bigPanel.setLayout(new GridLayout(10, 10));
for(int i=0; i<100; i++) {
bigPanel.add(new Button("Button " + i));
}
pane.add(bigPanel);
add(pane, BorderLayout.CENTER);
}
}
Aug 26
Five buttons arranged by FlowLayout
FlowTest.java
*************
FlowTest.java Five buttons arranged by FlowLayout
By default, FlowLayout arranges components in rows, left to right, and centered.
/././././././././././././
import java.applet.Applet;
import java.awt.*;
/** FlowLayout puts components in rows.
*
************************************
public class FlowTest extends Applet {
public void init() {
for(int i=1; i<6; i++) {
add(new Button("Button " + i));
}
}
}
Aug 26
A Frame that lets you draw circles with mouse clicks
SavedFrame.java
****************
A Frame that lets you draw circles with mouse clicks
//**************
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/** A Frame that lets you draw circles with mouse clicks
* and then save the Frame and all circles to disk.
*
public class SavedFrame extends CloseableFrame
implements ActionListener {
/** If a saved version exists, use it. Otherwise create a
* new one.
*/
public static void main(String[] args) {
SavedFrame frame;
File serializeFile = new File(serializeFilename);
if (serializeFile.exists()) {
try {
FileInputStream fileIn =
new FileInputStream(serializeFile);
ObjectInputStream in = new ObjectInputStream(fileIn);
frame = (SavedFrame)in.readObject();
frame.setVisible(true);
} catch(IOException ioe) {
System.out.println("Error reading file: " + ioe);
} catch(ClassNotFoundException cnfe) {
System.out.println("No such class: " + cnfe);
}
} else {
frame = new SavedFrame();
}
}
private static String serializeFilename ="SavedFrame.ser";
private CirclePanel circlePanel;
private Button clearButton, saveButton;
/** Build a frame with CirclePanel and buttons. */
public SavedFrame() {
super("SavedFrame");
setBackground(Color.white);
setFont(new Font("Serif", Font.BOLD, 18));
circlePanel = new CirclePanel();
add("Center", circlePanel);
Panel buttonPanel = new Panel();
buttonPanel.setBackground(Color.lightGray);
clearButton = new Button("Clear");
saveButton = new Button("Save");
buttonPanel.add(clearButton);
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.SOUTH);
clearButton.addActionListener(this);
saveButton.addActionListener(this);
setSize(300, 300);
setVisible(true);
}
/** If "Clear" clicked, delete all existing circles. If "Save"
* clicked, save existing frame configuration (size,
* location, circles, etc.) to disk.
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == clearButton) {
circlePanel.removeAll();
circlePanel.repaint();
} else if (event.getSource() == saveButton) {
try {
FileOutputStream fileOut =
new FileOutputStream("SavedFrame.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(this);
out.flush();
out.close();
} catch(IOException ioe) {
System.out.println("Error saving frame: " + ioe);
}
}
}
}
****************
Aug 26
FrameExample1.java and 2
******************
# FrameExample1.java
******************
import java.awt.*;
/**
*/
public class FrameExample1 {
public static void main(String[] args) {
Frame f = new Frame("Frame Example 1");
f.setSize(400, 300);
f.setVisible(true);
}
}
*********************
# FrameExample2.java
*********************
import java.awt.*;
/**
*/
public class FrameExample2 extends Frame {
public static void main(String[] args) {
new FrameExample2();
}
public FrameExample2() {
super("Frame Example 2");
setSize(400, 300);
setVisible(true);
}
}
**********************
Aug 26
ThreadedRSAKey.java Illustrates converting a method in an existing class from a single-threaded method to a multi-threaded method.
ThreadedRSAKey.java Illustrates converting a method in an existing class from a single-threaded method to a multi-threaded method. In this example, RSAKey computes an RSA public-private key pair, where the key size has a specified number of digits. As large prime numbers require considerable CPU time, ThreadedRSAKey converts the original computeKey method in RSAKey to a multi-threaded method, thus allowing simultaneous (multithreaded) computation of multiple key pairs. Uses the following classes:
import java.io.*;
* RSAKey.java Computes RSA public-private key pairs of arbitrary length.
* Primes.java Generates large prime numbers.
/** An example of creating a background process for an
* originally nonthreaded, class method. Normally,
* the program flow will wait until computeKey is finished.
public class ThreadedRSAKey extends RSAKey implements Runnable {
// Store strNumDigits into the thread to prevent race
// conditions.
public void computeKey(String strNumDigits) {
RSAThread t = new RSAThread(this, strNumDigits);
t.start();
}
// Retrieve the stored strNumDigits and call the original
// method. Processing is now done in the background.
public void run() {
RSAThread t = (RSAThread)Thread.currentThread();
String strNumDigits = t.getStrDigits();
super.computeKey(strNumDigits);
}
public static void main(String[] args){
ThreadedRSAKey key = new ThreadedRSAKey();
for (int i=0; i " + n);
System.out.println("public => " + encrypt);
System.out.println("private => " + decrypt);
}
}
* Primes.java Generates large prime numbers.
***
import java.math.BigInteger;
/** A few utilities to generate a large random BigInteger,
* and find the next prime number above a given BigInteger.
public class Primes {
// Note that BigInteger.ZERO was new in JDK 1.2, and 1.1
// code is being used to support the most servlet engines.
private static final BigInteger ZERO = new BigInteger("0");
private static final BigInteger ONE = new BigInteger("1");
private static final BigInteger TWO = new BigInteger("2");
// Likelihood of false prime is less than 1/2^ERR_VAL
// Assumedly BigInteger uses the Miller-Rabin test or
// equivalent, and thus is NOT fooled by Carmichael numbers.
// See section 33.8 of Cormen et al. Introduction to
// Algorithms for details.
private static final int ERR_VAL = 100;
public static BigInteger nextPrime(BigInteger start) {
if (isEven(start))
start = start.add(ONE);
else
start = start.add(TWO);
if (start.isProbablePrime(ERR_VAL))
return(start);
else
return(nextPrime(start));
}
private static boolean isEven(BigInteger n) {
return(n.mod(TWO).equals(ZERO));
}
private static StringBuffer[] digits =
{ new StringBuffer("0"), new StringBuffer("1"),
new StringBuffer("2"), new StringBuffer("3"),
new StringBuffer("4"), new StringBuffer("5"),
new StringBuffer("6"), new StringBuffer("7"),
new StringBuffer("8"), new StringBuffer("9") };
private static StringBuffer randomDigit() {
int index = (int)Math.floor(Math.random() * 10);
return(digits[index]);
}
public static BigInteger random(int numDigits) {
StringBuffer s = new StringBuffer("");
for(int i=0; i 0)
numDigits = Integer.parseInt(args[0]);
else
numDigits = 150;
BigInteger start = random(numDigits);
for(int i=0; i<50; i++) {
start = nextPrime(start);
System.out.println("Prime " + i + " = " + start);
}
}
}
Aug 26
Eight ungrouped buttons in an Applet using FlowLayout
mport java.applet.Applet; import java.awt.
*;
**************************
/** Eight ungrouped buttons in an Applet using FlowLayout. * */
public class ButtonTest1 extends Applet {
public void init() {
String[] labelPrefixes = {
"Start", "Stop", "Pause", "Resume"
};
for (int i=0; i<4; i++) {
add(new Button(labelPrefixes[i] + " Thread1"));
}
for (int i=0; i<4; i++) {
add(new Button(labelPrefixes[i] + " Thread2"));
}
}
}
Aug 26
A Circle component built using a Canvas
import java.awt.*;
/** A Circle component built using a Canvas.
*
*/
public class Circle extends Canvas {
private int width, height;
public Circle(Color foreground, int radius) {
setForeground(foreground);
width = 2*radius;
height = 2*radius;
setSize(width, height);
}
public void paint(Graphics g) {
g.fillOval(0, 0, width, height);
}
public void setCenter(int x, int y) {
setLocation(x - width/2, y - height/2);
}
}
Aug 26
Simplifies the setting of native look and feel
WindowUtilities.java Simplifies the setting of native look and feel.
####################
import javax.swing.*;
import java.awt.*; // For Color and Container classes.
/** A few utilities that simplify using windows in Swing.
*
###################
public class WindowUtilities {
/** Tell system to use native look and feel, as in previous
* releases. Metal (Java) LAF is the default otherwise.
*/
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}
/** A simplified way to see a JPanel or other Container. Pops
* up a JFrame with specified Container as the content pane.
*/
public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new ExitListener());
frame.setVisible(true);
return(frame);
}
/** Uses Color.white as the background color. */
public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height,
title, Color.white));
}
/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/
public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
}
