StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax
package cwp;
/** Simple bean to illustrate sharing beans through
* use of the scope attribute of jsp:useBean.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class AccessCountBean {
private String firstPage;
private int accessCount = 1;
public String getFirstPage() {
return(firstPage);
}
public void setFirstPage(String firstPage) {
this.firstPage = firstPage;
}
public int getAccessCount() {
return(accessCount++);
}
}
Aug 28
StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax
Aug 28
RepeatTag.java Custom tag that repeats the tag body a specified number of times
RepeatTag.java Custom tag that repeats the tag body a specified number of times
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** A tag that repeats the body the specified
* number of times.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class RepeatTag extends BodyTagSupport {
private int reps;
public void setReps(String repeats) {
try {
reps = Integer.parseInt(repeats);
} catch(NumberFormatException nfe) {
reps = 1;
}
}
public int doAfterBody() {
if (reps-- >= 1) {
BodyContent body = getBodyContent();
try {
JspWriter out = body.getEnclosingWriter();
out.println(body.getString());
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
System.out.println("Error in RepeatTag: " + ioe);
}
return(EVAL_BODY_TAG);
} else {
return(SKIP_BODY);
}
}
}
RepeatExample.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of RepeatTag tag.
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Some 40-Digit Primes</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1>Some 40-Digit Primes</H1>
Each entry in the following list is the first prime number
higher than a randomly selected 40-digit number.
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<OL>
<!-- Repeats N times. A null reps value means repeat once. -->
<cwp:repeat reps='<%= request.getParameter("repeats") %>'>
<LI><cwp:prime length="40" />
</cwp:repeat>
</OL>
</BODY>
</HTML>
Aug 28
An applet that reads arrays of strings packaged inside a QueryCollection and places them in a scrolling TextArea.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
/** Applet reads arrays of strings packaged inside
* a QueryCollection and places them in a scrolling
* TextArea. The QueryCollection obtains the strings
* by means of a serialized object input stream
* connected to the QueryGenerator servlet.
*
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* May be freely used or adapted.
*/
public class ShowQueries extends Applet
implements ActionListener, Runnable {
private TextArea queryArea;
private Button startButton, stopButton, clearButton;
private QueryCollection currentQueries;
private QueryCollection nextQueries;
private boolean isRunning = false;
private String address =
"/servlet/cwp.QueryGenerator";
private URL currentPage;
public void init() {
setBackground(Color.white);
setLayout(new BorderLayout());
queryArea = new TextArea();
queryArea.setFont(new Font("Serif", Font.PLAIN, 14));
add(queryArea, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
Font buttonFont = new Font("SansSerif", Font.BOLD, 16);
startButton = new Button("Start");
startButton.setFont(buttonFont);
startButton.addActionListener(this);
buttonPanel.add(startButton);
stopButton = new Button("Stop");
stopButton.setFont(buttonFont);
stopButton.addActionListener(this);
buttonPanel.add(stopButton);
clearButton = new Button("Clear TextArea");
clearButton.setFont(buttonFont);
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel, BorderLayout.SOUTH);
currentPage = getCodeBase();
// Request a set of sample queries. They
// are loaded in a background thread, and
// the applet checks to see if they have finished
// loading before trying to extract the strings.
currentQueries = new QueryCollection(address, currentPage);
nextQueries = new QueryCollection(address, currentPage);
}
/** If you press the "Start" button, the system
* starts a background thread that displays
* the queries in the TextArea. Pressing "Stop"
* halts the process, and "Clear" empties the
* TextArea.
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
if (!isRunning) {
Thread queryDisplayer = new Thread(this);
isRunning = true;
queryArea.setText("");
queryDisplayer.start();
showStatus("Started display thread...");
} else {
showStatus("Display thread already running...");
}
} else if (event.getSource() == stopButton) {
isRunning = false;
showStatus("Stopped display thread...");
} else if (event.getSource() == clearButton) {
queryArea.setText("");
}
}
/** The background thread takes the currentQueries
* object and every half-second places one of the queries
* the object holds into the bottom of the TextArea. When
* all of the queries have been shown, the thread copies
* the value of the nextQueries object into
* currentQueries, sends a new request to the server
* in order to repopulate nextQueries, and repeats
* the process.
*/
public void run() {
while(isRunning) {
showQueries(currentQueries);
currentQueries = nextQueries;
nextQueries = new QueryCollection(address, currentPage);
}
}
private void showQueries(QueryCollection queryEntry) {
// If request has been sent to server but the result
// isn't back yet, poll every second. This should
// happen rarely but is possible with a slow network
// connection or an overloaded server.
while(!queryEntry.isDone()) {
showStatus("Waiting for data from server...");
pause(1);
}
showStatus("Received data from server...");
String[] queries = queryEntry.getQueries();
String linefeed = "\n";
// Put a string into TextArea every half-second.
for(int i=0; i
Aug 28
FilterTag.java Custom tag that modifies the tag body
FilterTag.java Custom tag that modifies the tag body
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import cwp.*;
/** A tag that replaces <, >, ", and & with their HTML
* character entities (<, >, ", and &).
* After filtering, arbitrary strings can be placed
* in either the page body or in HTML attributes.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class FilterTag extends BodyTagSupport {
public int doAfterBody() {
BodyContent body = getBodyContent();
String filteredBody =
ServletUtilities.filter(body.getString());
try {
JspWriter out = body.getEnclosingWriter();
out.print(filteredBody);
} catch(IOException ioe) {
System.out.println("Error in FilterTag: " + ioe);
}
// SKIP_BODY means we're done. If we wanted to evaluate
// and handle the body again, we'd return EVAL_BODY_TAG.
return(SKIP_BODY);
}
}
Aug 28
An applet that searches multiple search engines, displaying the results in side-by-side frame cells.
Using Applets as Front Ends to Server-Side Programs
**************************************************
SearchApplet.java An applet that searches multiple search engines,
displaying the results in side-by-side frame cells. Uses the following files:
SearchSpec.javaParallelSearches.htmlSearchAppletFrame.htmlGoogleResultsFrame.htmlInfoseekResultsFrame.htmlLycosResultsFrame.html
***************************************************
//
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
//
/** An applet that reads a value from a TextField,
* then uses it to build three distinct URLs with embedded
* GET data: one each for Google, Infoseek, and Lycos.
* The browser is directed to retrieve each of these
* URLs, displaying them in side-by-side frame cells.
* Note that standard HTML forms cannot automatically
* perform multiple submissions in this manner.
*
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* May be freely used or adapted.
*/
public class SearchApplet extends Applet
implements ActionListener {
private TextField queryField;
private Button submitButton;
public void init() {
setBackground(Color.white);
setFont(new Font("Serif", Font.BOLD, 18));
add(new Label("Search String:"));
queryField = new TextField(40);
queryField.addActionListener(this);
add(queryField);
submitButton = new Button("Send to Search Engines");
submitButton.addActionListener(this);
add(submitButton);
}
/** Submit data when button is pressed or
* user presses Return in the TextField.
*/
public void actionPerformed(ActionEvent event) {
String query = URLEncoder.encode(queryField.getText());
SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs();
// Omitting HotBot (last entry), as they use JavaScript to
// pop result to top-level frame. Thus the length-1 below.
for(int i=0; i
Aug 28
RotationExample.java An example of translating and rotating the coordinate system prior to drawing
import java.awt.*;
/** An example of translating and rotating the coordinate
* system before each drawing.
*
*******************************
public class RotationExample extends StrokeThicknessExample {
private Color[] colors = { Color.white, Color.black };
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawThickCircleOutline(g2d);
// Move the origin to the center of the circle.
g2d.translate(185.0, 185.0);
for (int i=0; i<16; i++) {
// Rotate the coordinate system around current
// origin, which is at the center of the circle.
g2d.rotate(Math.PI/8.0);
g2d.setPaint(colors[i%2]);
g2d.drawString("Java", 0, 0);
}
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new RotationExample(),
380, 400);
}
}
Aug 28
Demonstrates setting the pen width (in pixels) using a BasicStroke prior to drawing. Inherits from FontExample.java.
StrokeThicknessExample.java
>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;
/** An example of controlling the Stroke (pen) widths when
* drawing.
*
******************
*/
public class StrokeThicknessExample extends FontExample {
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawBigString(g2d);
drawThickCircleOutline(g2d);
}
protected void drawThickCircleOutline(Graphics2D g2d) {
g2d.setPaint(Color.blue);
g2d.setStroke(new BasicStroke(8)); // 8-pixel wide pen
g2d.draw(getCircle());
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new StrokeThicknessExample(),
380, 400);
}
}
Aug 28
ListFonts.java Lists all local fonts available for graphical drawing.
ListFonts.java Lists all local fonts available for graphical drawing.
***********************
import java.awt.*;
/** Lists the names of all available fonts.
*
******************
public class ListFonts {
public static void main(String[] args) {
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = env.getAvailableFontFamilyNames();
System.out.println("Available Fonts:");
for(int i=0; i>>>>>>>>>>>>>>>>>>>>>>>
Aug 28
Illustrates the effect of different transparency
~~~~~~~~~~~~~~~~~~~
TransparencyExample.java Illustrates the effect of different transparency (alpha) values when drawing a shape.
~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
/** An illustration of the use of AlphaComposite to make
* partially transparent drawings.
*
**********************************
public class TransparencyExample extends JPanel {
private static int gap=10, width=60, offset=20,
deltaX=gap+width+offset;
private Rectangle
blueSquare = new Rectangle(gap+offset, gap+offset, width,
width),
redSquare = new Rectangle(gap, gap, width, width);
private AlphaComposite makeComposite(float alpha) {
int type = AlphaComposite.SRC_OVER;
return(AlphaComposite.getInstance(type, alpha));
}
private void drawSquares(Graphics2D g2d, float alpha) {
Composite originalComposite = g2d.getComposite();
g2d.setPaint(Color.blue);
g2d.fill(blueSquare);
g2d.setComposite(makeComposite(alpha));
g2d.setPaint(Color.red);
g2d.fill(redSquare);
g2d.setComposite(originalComposite);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0; i<11; i++) {
drawSquares(g2d, i*0.1F);
g2d.translate(deltaX, 0);
}
}
public static void main(String[] args) {
String title = "Transparency example: alpha of the top " +
"(red) square ranges from 0.0 at the left " +
"to 1.0 at the right. Bottom (blue) square " +
"is opaque.";
WindowUtilities.openInJFrame(new TransparencyExample(),
11*deltaX + 2*gap,
deltaX + 3*gap,
title, Color.lightGray);
}
}
>>>>>>>>>>>>>>>>>>
Aug 27
Handling Events
***********************************
* ActionExample1.java Inherits from CloseableFrame.java and uses SetSizeButton.java.
* ActionExample2.java Inherits from CloseableFrame.java.
**********************************************************
ActionExample1.java
*******************
import java.awt.*;
public class ActionExample1 extends CloseableFrame {
public static void main(String[] args) {
new ActionExample1();
}
public ActionExample1() {
super("Handling Events in Component");
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18));
add(new SetSizeButton(300, 200));
add(new SetSizeButton(400, 300));
add(new SetSizeButton(500, 400));
setSize(400, 300);
setVisible(true);
}
}
********************
CloseableFrame.java
********************
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);
}
}
}
**********************
SetSizeButton.java
**********************
import java.awt.*;
import java.awt.event.*;
///////////////////////
public class SetSizeButton extends Button
implements ActionListener {
private int width, height;
public SetSizeButton(int width, int height) {
super("Resize to " + width + "x" + height);
this.width = width;
this.height = height;
addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
getParent().setSize(width, height);
getParent().invalidate();
getParent().validate();
}
}
***********************
ActionExample2.java
***********************
import java.awt.*;
import java.awt.event.*;
/***********/
public class ActionExample2 extends CloseableFrame
implements ActionListener {
public static void main(String[] args) {
new ActionExample2();
}
private Button button1, button2, button3;
public ActionExample2() {
super("Handling Events in Other Object");
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18));
button1 = new Button("Resize to 300x200");
button2 = new Button("Resize to 400x300");
button3 = new Button("Resize to 500x400");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
add(button1);
add(button2);
add(button3);
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button1) {
updateLayout(300, 200);
} else if (event.getSource() == button2) {
updateLayout(400, 300);
} else if (event.getSource() == button3) {
updateLayout(500, 400);
}
}
private void updateLayout(int width, int height) {
setSize(width, height);
invalidate();
validate();
}
}
****************/>
CloseableFrame.java.
****************/><
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);
}
}
}
***************
