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
An applet that searches multiple search engines, displaying the results in side-by-side frame cells.
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);
}
}
}
***************
Aug 27
A Frame that uses the Confirm dialog to verify quit
ConfirmTest.java
****************
import java.awt.*;
import java.awt.event.*;
/** A Frame that uses the Confirm dialog to verify that
* users really want to quit.
*
public class ConfirmTest extends Frame {
public static void main(String[] args) {
new ConfirmTest();
}
public ConfirmTest() {
super("Confirming QUIT");
setSize(200, 200);
addWindowListener(new ConfirmListener());
setVisible(true);
}
public ConfirmTest(String title) {
super(title);
}
private class ConfirmListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
new Confirm(ConfirmTest.this);
}
}
}
****************
Confirm.java
****************
dialog box with two buttons: Yes and No
****************
import java.awt.*;
import java.awt.event.*;
/** A modal dialog box with two buttons: Yes and No.
* Clicking Yes exits Java. Clicking No exits the
* dialog. Used for confirmed quits from frames.
********************
class Confirm extends Dialog implements ActionListener {
private Button yes, no;
public Confirm(Frame parent) {
super(parent, "Confirmation", true);
setLayout(new FlowLayout());
add(new Label("Really quit?"));
yes = new Button("Yes");
yes.addActionListener(this);
no = new Button("No");
no.addActionListener(this);
add(yes);
add(no);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == yes) {
System.exit(0);
} else {
dispose();
}
}
}
***************
Aug 27
CircleDrawer3.java Applet that uses a named nested class to handle mouse events and draw circles. Illustrates third approach to event-handling with listeners: using inner classes.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/** Draw circles centered where the user clicks.
* Uses named inner classes.
*
******************
public class CircleDrawer3 extends Applet {
public void init() {
setForeground(Color.blue);
addMouseListener(new CircleListener());
}
private class CircleListener extends MouseAdapter {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
}
}
Aug 27
Applet handle mouse events
ClickReporter.java A simple applet that uses the class to handle mouse events
import java.applet.Applet; import java.awt.*; /** Prints a message saying where the user clicks. * Uses an external listener. *
public class ClickReporter extends Applet {
public void init() {
setBackground(Color.yellow);
addMouseListener(new ClickListener());
}
}
Aug 27
Custom AWT Slider
*****************
Custom AWT Slider
* LabeledCostSlider.java. A numeric slider class with attached label.
* CostSlider.java. A slider class that lets you read numeric values. Used in the LabeledCostSlider class.
* Slider.java. A slider class: a combination of Scrollbar and TextField. Used in the CostSlider class.
* ScrollbarPanel.java A Panel with adjustable top and bottom insets, used by the Slider class to change the thickness of the Slider.
*****************
LabeledCostSlider.java. A numeric slider class with attached label.
>>>>>>>>>>>>>>>>>
import java.awt.*;
/** A CostSlider with a label centered above it.
*************
public class LabeledCostSlider extends Panel {
public LabeledCostSlider(String labelString,
Font labelFont,
int minValue, int maxValue,
int initialValue,
Everest app) {
setLayout(new BorderLayout());
Label label = new Label(labelString, Label.CENTER);
if (labelFont != null) {
label.setFont(labelFont);
}
add(label, BorderLayout.NORTH);
CostSlider slider = new CostSlider(minValue,
maxValue,
initialValue,
app);
add(slider, BorderLayout.CENTER);
}
}
<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>
CostSlider.java. A slider class that lets you read numeric values. Used in the LabeledCostSlider class.
>>>>>>>>>>>>>>>>>>>
/** A Slider that takes an Everest applet as an argument,
* calling back to its setCostField when the slider value
* changes.
*
*******************
public class CostSlider extends Slider {
private Everest app;
public CostSlider(int minValue, int maxValue,
int initialValue, Everest app) {
super(minValue, maxValue, initialValue);
this.app = app;
}
public void doAction(int value) {
app.setCostField(value);
}
}
<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>
Slider.java. A slider class: a combination of Scrollbar and TextField. Used in the CostSlider class.
>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.event.*;
/** A class that combines a horizontal Scrollbar and a TextField
* (to the right of the Scrollbar). The TextField shows the
* current scrollbar value, plus, if setEditable(true) is set,
* it can be used to change the value as well.
*
********************
public class Slider extends Panel implements ActionListener,
AdjustmentListener {
private Scrollbar scrollbar;
private TextField textfield;
private ScrollbarPanel scrollbarPanel;
private int preferredWidth = 250;
/** Construct a slider with the specified min, max and initial
* values. The "bubble" (thumb) size is set to 1/10th the
* scrollbar range.
*/
public Slider(int minValue, int maxValue, int initialValue) {
this(minValue, maxValue, initialValue,
(maxValue - minValue)/10);
}
/** Construct a slider with the specified min, max,and initial
* values, plus the specified "bubble" (thumb) value. This
* bubbleSize should be specified in the units that min and
* max use, not in pixels. Thus, if min is 20 and max is 320,
* then a bubbleSize of 30 is 10% of the visible range.
*/
public Slider(int minValue, int maxValue, int initialValue,
int bubbleSize) {
setLayout(new BorderLayout());
maxValue = maxValue + bubbleSize;
scrollbar = new Scrollbar(Scrollbar.HORIZONTAL,
initialValue, bubbleSize,
minValue, maxValue);
scrollbar.addAdjustmentListener(this);
scrollbarPanel = new ScrollbarPanel(6);
scrollbarPanel.add(scrollbar, BorderLayout.CENTER);
add(scrollbarPanel, BorderLayout.CENTER);
textfield = new TextField(numDigits(maxValue) + 1);
textfield.addActionListener(this);
setFontSize(12);
textfield.setEditable(false);
setTextFieldValue();
add(textfield, BorderLayout.EAST);
}
/** A place holder to override for action to be taken when
* scrollbar changes.
*/
public void doAction(int value) {
}
/** When textfield changes, sets the scrollbar */
public void actionPerformed(ActionEvent event) {
String value = textfield.getText();
int oldValue = getValue();
try {
setValue(Integer.parseInt(value.trim()));
} catch(NumberFormatException nfe) {
setValue(oldValue);
}
}
/** When scrollbar changes, sets the textfield */
public void adjustmentValueChanged(AdjustmentEvent event) {
setTextFieldValue();
doAction(scrollbar.getValue());
}
/** Returns the Scrollbar part of the Slider. */
public Scrollbar getScrollbar() {
return(scrollbar);
}
/** Returns the TextField part of the Slider */
public TextField getTextField() {
return(textfield);
}
/** Changes the preferredSize to take a minimum width, since
* super-tiny scrollbars are hard to manipulate.
*/
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = textfield.getPreferredSize().height;
d.width = Math.max(d.width, preferredWidth);
return(d);
}
/** This just calls preferredSize */
public Dimension getMinimumSize() {
return(getPreferredSize());
}
/** To keep scrollbars legible, a minimum width is set. This
* returns the current value (default is 150).
*/
public int getPreferredWidth() {
return(preferredWidth);
}
/** To keep scrollbars legible, a minimum width is set. This
* sets the current value (default is 150).
*/
public void setPreferredWidth(int preferredWidth) {
this.preferredWidth = preferredWidth;
}
/** This returns the current scrollbar value */
public int getValue() {
return(scrollbar.getValue());
}
/** This assigns the scrollbar value. If it is below the
* minimum value or above the maximum, the value is set to
* the min and max value, respectively.
*/
public void setValue(int value) {
scrollbar.setValue(value);
setTextFieldValue();
}
/** Sometimes horizontal scrollbars look odd if they are very
* tall. So empty top/bottom margins can be set. This returns
* the margin setting. The default is four.
*/
public int getMargins() {
return(scrollbarPanel.getMargins());
}
/** Sometimes horizontal scrollbars look odd if they are very
* tall. So empty top/bottom margins can be set. This sets
* the margin setting.
*/
public void setMargins(int margins) {
scrollbarPanel.setMargins(margins);
}
/** Returns the current textfield string. In most cases this
* is just the same as a String version of getValue, except
* that there may be padded blank spaces at the left.
*/
public String getText() {
return(textfield.getText());
}
/** This sets the TextField value directly. Use with extreme
* caution since it does not right-align or check if value
* is numeric.
*/
public void setText(String text) {
textfield.setText(text);
}
/** Returns the Font being used by the textfield.
* Courier bold 12 is the default.
*/
public Font getFont() {
return(textfield.getFont());
}
/** Changes the Font being used by the textfield. */
public void setFont(Font textFieldFont) {
textfield.setFont(textFieldFont);
}
/** The size of the current font */
public int getFontSize() {
return(getFont().getSize());
}
/** Rather than setting the whole font, you can just set the
* size (Monospaced bold will be used for the family/face).
*/
public void setFontSize(int size) {
setFont(new Font("Monospaced", Font.BOLD, size));
}
/** Determines if the textfield is editable. If it is, you can
* enter a number to change the scrollbar value. In such a
* case, entering a value outside the legal range results in
* the min or max legal value. A non-integer is ignored.
*/
public boolean isEditable() {
return(textfield.isEditable());
}
/** Determines if you can enter values directly into the
* textfield to change the scrollbar.
*/
public void setEditable(boolean editable) {
textfield.setEditable(editable);
}
// Sets a right-aligned textfield number.
private void setTextFieldValue() {
int value = scrollbar.getValue();
int digits = numDigits(scrollbar.getMaximum());
String valueString = padString(value, digits);
textfield.setText(valueString);
}
// Repeated String concatenation is expensive, but this is
// only used to add a small amount of padding, so converting
// to a StringBuffer would not pay off.
private String padString(int value, int digits) {
String result = String.valueOf(value);
for(int i=result.length(); i>>>>>>>>>>>>>>>>>>>
ScrollbarPanel.java A Panel with adjustable top and bottom insets, used by the Slider class to change the thickness of the Slider.
>>>>>>>>>>>>>>>>>>>
import java.awt.*;
/** A Panel with adjustable top/bottom insets value.
* Used to hold a Scrollbar in the Slider class.
*
*******************
public class ScrollbarPanel extends Panel {
private Insets insets;
public ScrollbarPanel(int margins) {
setLayout(new BorderLayout());
setMargins(margins);
}
public Insets insets() {
return(insets);
}
public int getMargins() {
return(insets.top);
}
public void setMargins(int margins) {
this.insets = new Insets(margins, 0, margins, 0);
}
}
<<<<<<<<<<<<<<<<<<<<<
