/./././././././././.
// 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
Using the this reference in class Ship3
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
Aug 26
A Frame that can actually quit
import java.awt.*;
import java.awt.event.*;
/** A Frame that you can actually quit. Used as the starting
* point for most Java 1.1 graphical applications.
*
public class CloseableFrame extends Frame {
public CloseableFrame(String title) {
super(title);
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
}
/** Since we are doing something permanent, we need
* to call super.processWindowEvent first.
*/
public void processWindowEvent(WindowEvent event) {
super.processWindowEvent(event); // Handle listeners.
if (event.getID() == WindowEvent.WINDOW_CLOSING) {
// If the frame is used in an applet, use dispose().
System.exit(0);
}
}
}
Aug 26
creating a simple Swing application using a JFrame
JFrameExample.java Demonstrates creating a simple Swing application using a JFrame. As with a JApplet, components must be added to the content pane, instead of the window directly.import java.awt.*;
import javax.swing.*;
/** Tiny example showing the main difference in using
* JFrame instead of Frame: using the content pane
* and getting the Java (Metal) look and feel by default
* instead of the native look and feel.
*
*/
public class JFrameExample {
public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
f.addWindowListener(new ExitListener());
f.setVisible(true);
}
}
Aug 26
Explicit placement of five buttons with the layout manager turned off
NullTest.java Explicit placement of five buttons with the layout manager turned off (set to null)
##########################
import java.applet.Applet;
import java.awt.*;
/** Layout managers are intended to help you, but there
* is no law saying you have to use them.
* Set the layout to null to turn them off.
*
*******************
public class NullTest extends Applet {
public void init() {
setLayout(null);
Button b1 = new Button("Button 1");
Button b2 = new Button("Button 2");
Button b3 = new Button("Button 3");
Button b4 = new Button("Button 4");
Button b5 = new Button("Button 5");
b1.setBounds(0, 0, 150, 50);
b2.setBounds(150, 0, 75, 50);
b3.setBounds(225, 0, 75, 50);
b4.setBounds(25, 60, 100, 40);
b5.setBounds(175, 60, 100, 40);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
}
Aug 26
JTree Examples
SimpleTree.java Basic tree built out of DefaultMutableTreeNodes. A DefualtMutableTreeNode is a starting point for a root node, in which children nodes can be added.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
/** Example tree built out of DefaultMutableTreeNodes.
*
*/
public class SimpleTree extends JFrame {
public static void main(String[] args) {
new SimpleTree();
}
public SimpleTree() {
super("Creating a Simple JTree");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
Object[] hierarchy =
{ "javax.swing",
"javax.swing.border",
"javax.swing.colorchooser",
"javax.swing.event",
"javax.swing.filechooser",
new Object[] { "javax.swing.plaf",
"javax.swing.plaf.basic",
"javax.swing.plaf.metal",
"javax.swing.plaf.multi" },
"javax.swing.table",
new Object[] { "javax.swing.text",
new Object[] { "javax.swing.text.html",
"javax.swing.text.html.parser" },
"javax.swing.text.rtf" },
"javax.swing.tree",
"javax.swing.undo" };
DefaultMutableTreeNode root = processHierarchy(hierarchy);
JTree tree = new JTree(root);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(275, 300);
setVisible(true);
}
/** Small routine that will make a node out of the first entry
* in the array, then make nodes out of subsequent entries
* and make them child nodes of the first one. The process
* is repeated recursively for entries that are arrays.
*/
private DefaultMutableTreeNode processHierarchy(
Object[] hierarchy) {
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(hierarchy[0]);
DefaultMutableTreeNode child;
for(int i=1; i 0) {
try {
n = Integer.parseInt(args[0]);
} catch(NumberFormatException nfe) {
System.out.println(
"Can't parse number; using default of " + n);
}
}
new DynamicTree(n);
}
public DynamicTree(int n) {
super("Creating a Dynamic JTree");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JTree tree = new JTree(new OutlineNode(1, n));
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(300, 475);
setVisible(true);
}
}
* OutlineNode.java A simple tree node that builds its children.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
/** Simple TreeNode that builds children on the fly.
* The key idea is that getChildCount is always called before
* any actual children are requested. That way, getChildCount
* builds the children if they don't already exist.
*
* In this case, it just builds an "outline" tree. I.e.,
* if the root is current node is "x", the children are
* "x.0", "x.1", "x.2", and "x.3".
*
*
*/
public class OutlineNode extends DefaultMutableTreeNode {
private boolean areChildrenDefined = false;
private int outlineNum;
private int numChildren;
public OutlineNode(int outlineNum, int numChildren) {
this.outlineNum = outlineNum;
this.numChildren = numChildren;
}
public boolean isLeaf() {
return(false);
}
public int getChildCount() {
if (!areChildrenDefined) {
defineChildNodes();
}
return(super.getChildCount());
}
private void defineChildNodes() {
// You must set the flag before defining children if you
// use "add" for the new children. Otherwise, you get an
// infinite recursive loop since add results in a call
// to getChildCount. However, you could use "insert" in such
// a case.
areChildrenDefined = true;
for(int i=0; i
Aug 26
Printing in Java 2
*
o PrintExample.java Demonstrates printing a Graphics2D object.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.*;
/** An example of a printable window in Java 1.2. The key point
* here is that any component is printable in Java 1.2.
* However, you have to be careful to turn off double buffering
* globally (not just for the top-level window).
* See the PrintUtilities class for the printComponent method
* that lets you print an arbitrary component with a single
* function call.
*
*/
public class PrintExample extends JFrame
implements ActionListener {
public static void main(String[] args) {
new PrintExample();
}
public PrintExample() {
super("Printing Swing Components in JDK 1.2");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
PrintUtilities.printComponent(this);
}
}
Uses the following classes:
+ PrintUtilities.java Simple utility class to support printing graphical windows in JDK 1.2.
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class that lets you very simply print
* an arbitrary component in JDK 1.2. Just pass the
* component to PrintUtilities.printComponent. The
* component you want to print doesn't need a print method
* and doesn't have to implement any interface or do
* anything special at all.
*
* If you are going to be printing many times, it is marginally
* more efficient to first do the following:
*
* PrintUtilities printHelper =
* new PrintUtilities(theComponent);
*
* then later do printHelper.print(). But this is a very tiny
* difference, so in most cases just do the simpler
* PrintUtilities.printComponent(componentToBePrinted).
*
*/
public class PrintUtilities implements Printable {
protected Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
}
public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
// General print routine for JDK 1.2. Use PrintUtilities2
// for printing in JDK 1.3.
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(),
pageFormat.getImageableY());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on,
* so this turns it off globally. This step is only
* required in JDK 1.2.
*/
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager =
RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
/** Reenables double buffering globally. This step is only
* required in JDK 1.2.
*/
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager =
RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
}
//
+ DrawingPanel.java A basic JPanel containing a Java 2D drawing.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
/** A window with a custom paintComponent method.
* Illustrates that you can make a general-purpose method
* that can print any component, regardless of whether
* that component performs custom drawing.
* See the PrintUtilities class for the printComponent method
* that lets you print an arbitrary component with a single
* function call.
*
*/
public class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}
/** Draws a black string with a tall angled "shadow"
* of the string behind it.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
o PrintUtilities2.java Simple utility class to support printing graphical windows in JDK 1.3 and later. Inherits from PrintUtilities.java.
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class for printing an arbitrary
* component in JDK 1.3. The class relies on the
* fact that in JDK 1.3 the JComponent class overrides
* print (in Container) to automatically set a flag
* that disables double buffering before the component
* is painted. If the printing flag is set, paint calls
* printComponent, printBorder, and printChildren.
*
* To print a component, just pass the component to
* PrintUtilities2.printComponent(componentToBePrinted).
*
*/
public class PrintUtilities2 extends PrintUtilities {
public static void printComponent(Component c) {
new PrintUtilities2(c).print();
}
public PrintUtilities2(Component componentToBePrinted) {
super(componentToBePrinted);
}
// General print routine for JDK 1.3. Use PrintUtilities1
// for printing in JDK 1.2.
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(),
pageFormat.getImageableY());
componentToBePrinted.print(g2d);
return(PAGE_EXISTS);
}
}
}
* FileTransfer.java Demonstrates the proper technique for updating Swing components in a multithreaded program.
/**
// Final version of FileTransfer. Modification of the
// label is thread safe.
public class FileTransfer extends Thread {
private String filename;
private JLabel label;
public FileTransfer(String filename, JLabel label) {
this.filename = filename;
this.label = label;
}
public void run() {
try {
// Place the runnable object to update the label
// on the event queue. The invokeAndWait method
// will block until the label is updated.
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
label.setText("Transferring " + filename);
}
});
} catch(InvocationTargetException ite) {
} catch(InterruptedException ie) { }
// Transfer file to server. Lengthy process.
doTransfer(...);
// Perform the final update to the label from
// within the runnable object. Use invokeLater;
// blocking is not necessary.
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
label.setText("Transfer completed");
}
});
}
}
* WindowUtilities.java Utility class that simplifies creating a window and setting the look and feel.
* ExitListener.java A WindowListener with support to close the window.
