******************
# 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
FrameExample1.java and 2
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));
}
}
Aug 26
Using the this reference in class Ship3
/./././././././././.
// Give Ship3 a constructor to let the instance variables
// be specified when the object is created.
/./././././././././
class Ship3 {
public double x, y, speed, direction;
public String name;
public Ship3(double x, double y, double speed,
double direction, String name) {
this.x = x; // "this" differentiates instance vars
this.y = y; // from local vars.
this.speed = speed;
this.direction = direction;
this.name = name;
}
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
}
public void move() {
double angle = degreesToRadians(direction);
x = x + speed * Math.cos(angle);
y = y + speed * Math.sin(angle);
}
public void printLocation() {
System.out.println(name + " is at " +
"(" + x + "," + y + ").");
}
}
public class Test3 {
public static void main(String[] args) {
Ship3 s1 = new Ship3(0.0, 0.0, 1.0, 0.0, "Ship1");
Ship3 s2 = new Ship3(0.0, 0.0, 2.0, 135.0, "Ship2");
s1.move();
s2.move();
s1.printLocation();
s2.printLocation();
}
}
Aug 26
DashedStrokeExample.java Draws a circle with a dashed line segment (border). Inherits from FontExample.java.
>>>>>>>>>>>>>>>>>
import java.awt.*;
/** An example of creating a custom dashed line for drawing.
*
*********************
public class DashedStrokeExample extends FontExample {
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawBigString(g2d);
drawDashedCircleOutline(g2d);
}
protected void drawDashedCircleOutline(Graphics2D g2d) {
g2d.setPaint(Color.blue);
// 30-pixel line, 10-pixel gap, 10-pixel line, 10-pixel gap
float[] dashPattern = { 30, 10, 10, 10 };
g2d.setStroke(new BasicStroke(8, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10,
dashPattern, 0));
g2d.draw(getCircle());
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new DashedStrokeExample(),
380, 400);
}
}
<<<<<<<<<<<<<<
Aug 26
draws a circle wherever mouse was pressed
CircleListener.java A subclass of MouseAdapter that draws a circle wherever mouse was pressed. Illustrates first approach to event-handling with listeners: attaching a separate listener
***********
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/** The listener used by CircleDrawer1. Note call
* to getSource to obtain reference to the applet.
*
***************
public class CircleListener extends MouseAdapter {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Applet app = (Applet)event.getSource();
Graphics g = app.getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
}
Aug 26
Six buttons arranged in a 2 row x 3 column grid by GridLayout
/././././././
GridTest.java Six buttons arranged in a 2 row x 3 column grid by GridLayout.GridLayout divides the window into equal-sized rectangles based upon the number of rows and columns specified.
******************
import java.applet.Applet;
import java.awt.*;
/** An example of GridLayout.
*
/./././././.
public class GridTest extends Applet {
public void init() {
setLayout(new GridLayout(2,3)); // 2 rows, 3 cols
add(new Button("Button One"));
add(new Button("Button Two"));
add(new Button("Button Three"));
add(new Button("Button Four"));
add(new Button("Button Five"));
add(new Button("Button Six"));
}
}
Aug 26
ListEvent2.java
# ListEvents.java Uses the following classes:
* CloseableFrame.java
* SelectionReporter.java
* ActionReporter.java
/././././././././././././
import java.awt.event.*;
/././././././
public class ListEvents2 extends ListEvents {
public static void main(String[] args) {
new ListEvents2();
}
/** Extends ListEvents with the twist that
* typing any of the letters of "JAVA" or "java"
* over the language list will result in "Java"
* being selected
*/
public ListEvents2() {
super();
// Create a KeyAdapter and attach it to languageList.
// Since this is an inner class, it has access
// to nonpublic data (such as the ListEvent's
// protected showJava method).
KeyAdapter javaChooser = new KeyAdapter() {
public void keyPressed(KeyEvent event) {
int key = event.getKeyChar();
if ("JAVAjava".indexOf(key) != -1) {
showJava();
}
}
};
languageList.addKeyListener(javaChooser);
}
}
***************************
import java.awt.*;
import java.awt.event.*;
/** A class to demonstrate list selection/deselection
* and action events.
*
/*******************/.>
public class ListEvents extends CloseableFrame {
public static void main(String[] args) {
new ListEvents();
}
protected List languageList;
private TextField selectionField, actionField;
private String selection = "[NONE]", action;
/** Build a Frame with list of language choices
* and two textfields to show the last selected
* and last activated items from this list.
*/
public ListEvents() {
super("List Events");
setFont(new Font("Serif", Font.BOLD, 16));
add(makeLanguagePanel(), BorderLayout.WEST);
add(makeReportPanel(), BorderLayout.CENTER);
pack();
setVisible(true);
}
// Create Panel containing List with language choices.
// Constructor puts this at left side of Frame.
private Panel makeLanguagePanel() {
Panel languagePanel = new Panel();
languagePanel.setLayout(new BorderLayout());
languagePanel.add(new Label("Choose Language"),
BorderLayout.NORTH);
languageList = new List(3);
String[] languages =
{ "Ada", "C", "C++", "Common Lisp", "Eiffel",
"Forth", "Fortran", "Java", "Pascal",
"Perl", "Scheme", "Smalltalk" };
for(int i=0; i
