LIBRARY OF PROGRAMS THAT USE JAVA SWING AND JAVA 2D

To view these programs you will need a browser that supports Java 1.2, Java 1.3, or Java 2. That is, Netscape 4.x with appropriate plugins, or Java-enabled versions of Netscape 6 and Microsoft IE 5.


SIMPLE SWING APPLETS

PROGRAM AND SOURCE CODE

Simple Applet and Standalone Program. This program displays a "text" string on a graphical window, and can be run as a standalone program or an applet.

Run the program
Source code : HelloSwing.java
Demonstrate Anatomy of a Swing Applet. This program is adapted from the Java Tutorial book and shows the sequence of methods called when an applet is initialized (i.e., ..init() then ...start()). The ..destroy() and ..stop() methods can be activated by running this program with the appletviewer.

Run the program
Source code : AppletAnatomy.java
WORKING WITH IMAGES
Download and Display Image. This simple applet displays a text string and "turtle" image. In the source code file, notice how the image URL is assembled from the codebase URL concatenated to the Turtle.jpg file name.

Run the program
Source code : DemoTurtle.java
WORKING WITH LAYOUT MANAGERS

BorderLayout. The default layout manager for Java applets is border layout. This applet creates five buttons and then positions them using border layout (SOUTH, NORTH, WEST, EAST and CENTER).


Run the program
Source code : DemoBorderLayout.java

FlowLayout. Flow layout is the default layout manager for standalone Java programs, and hence, use of the flow layout must be programmed for Java applets. This applet positions five buttons on a content pane using the flow layout manager. Adapted from Pure JFC Swing by S. Pantham, 1999.


Run the program
Source code : DemoFlowLayout.java

GridLayout. This applet uses the grid layout manager.to position twelve buttons in a four-by-three grid. Adapted from Pure JFC Swing by S. Pantham, 1999.


Run the program
Source code : DemoGridLayout.java

CardLayout. This applet contains two cards, the first panel contains four buttons linked to URLs of software companies, the second buttons to aerospace companies (URLs are not implemented). Details are as follows:

   Card 1 : Software Company sites
            JavaSoft, Sun, IBM, Boeing
   Card 2 : Aerospace Company sites
            NASA, Boeing, Lockheed, Northrop.

The control panel contains "next" and "previous" buttons to flip between the card layout panels. Adapted from Pure JFC Swing by S. Pantham, 1999.

Run the program
Source code : DemoCardLayout.java

GridBagLayout. This applet uses the gridbag layout manager to display four buttons. Abbreviated details of the layout parameters are as follows:

c.insets = new Insets(5,5,5,5) : Specifies the external padding for a component, the spacing between the components and boundaries of its display area. In this example the (x,y) coordinates range from (0,0) in the upper left-hand corner to (x,y) = (5,5) in the bottom right-hand corner. Vertical and horizontal spacing between components is 5 pixels. c.gridx and g.gridy : These fields represent the x and y cell coordinates in the gridbag layout. c.gridwidth and c.gridheight : These fields specify the sise of the component in terms of cells. c.weightx and c.weighty : These fields specify how to distribute the extra horizontal and vertical space, while resisting the container. When c.weightx and c.weighty equal 1, the components expand to occupy extra space in the horizontal and vertical directions. Adapted from Pure JFC Swing by S. Pantham, 1999.


Run the program
Source code : DemoGridBagLayout.java
DEMONSTRATE HANDLING OF EVENTS
Low-level Mouse Events. This applet exercises low-level mouse events, and monitors and prints an appropriate message when the cursor enters and exits the applet border, and when the mouse is clicked and released. When a mouse is pressed and released at the same coordinate, the applet prints "clicked here!"

The Swing class JApplet contains the update() method to override the same method from the class Component that repairs the container background with its background color and calls the paint() method. The update() method in JApplet does not repair the background of the container. Instead, it calls the paint() method. You need to use an update() method that repairs the background.


Run the program
Source code : DemoMouse.java
Mouse Motion Events. When you click on the applet and move the mouse the cursor coordinates will be printed to the canvas. This applet uses the update() method to repair the applet's background, thereby reducing performance and leading to flickering. The workaround is to use a JPanel attached to the applet.

Run the program
Source code : DemoMouseMotion.java
Action Event Listeners. This applet demonstrates use of sources, events, and action event listeners. It displays a button and a label showing a "bell" image. Click on the button to ring the bell three times!!

Run the program
Source code : DemoActionEvent.java
BASIC SWING COMPONENTS
Buttons. This program is an "applet" version of the three buttons example given in the Java Tutorial book (Campione et al.). In this example, we position the buttons using a 1-by-3 grid layout manageer. The action event manager enables and disables the buttons.

Run the program
Source code : ButtonDemo.java

Slider. A slider is a control mechanism with a pointer knob that can slide on a continuous range of values to select a specific value of the parameter for which the widge has been used. A common application of sliders is audio volumes, ... etc. This applet demonstrates APIs from the class JSlider. Check out the coupling of the slider settings to the left-right button.


Run the program
Source code : DemoSlider.java

Scroll Pane. This applet displays an image inside a scrollpane, in this case, a label displaying an image downloaded from the server. A scroll pane is used to display a child component with a built-in scrolling capability. Scroll bars in the horizontal and vertical directions are automatically provided when the child compoent's size is too large to fit on the available viewport.


Run the program
Source code : DemoScrollPane.java

Tabbed Pane. Tabbed panes allow developers to stack pages of information into a single point of reference. Each page in a tabbed pane is implemented as a panel. Further Java UI components are added to the panel. This applet implements a tabbed pane containing three pages: page 1 contains a text field window and a password textfield; page 2 contains five buttons positioned with a border layout; page 3 contains contains three labels and three scrolling textarea windows positioned with a 3-by-2 grid layout.


Run the program
Source code : DemoTabbedPane.java

Scroll Bars. Scroll bars contain a scroll knob that slides along a bar attached with small end-buttons. This applet demonstrates the JScrollBar class, and shows how properties of the scrollbar change when the scroll knob value is adjusted. The applet also show which scroll bar (vertical or horizontal) is active.


Run the program
Source code : DemoScrollBar.java

Text Fields and Text Areas. Using the text area component, multiple lines of text can be displayed and edited. This applet exercises the capabilities of the class JTextArea. The contents of the text area may be manipulated by using the text field and buttons displayed. A message may be typed in the text field box and then positioned using the button operations. You can also select a text segment and press delete to remove it. Other buttons are used for cat, copy and paste.


Run the program
Source code : DemoTextArea.java

Color Chooser. This applet is a simple drawing program with color chooser ... check it out!!! Notice how the color chooser is activated via an action listener and details of the drawing are handled by mouse listeners.


Run the program
Source code : DemoColorChooser.java
WORKING WITH MENUS AND TOOLBARS

Menu Bar. Create bar of menu items -- file, edit, format, options -- together with small red-dot gif images.


Run the program
Source code : DemoMenuBar.java

Menu Bar with Pulldown Submenus. Create menu bar (file, edit, options) together with pull-down submenus. The options pulldown menu has "book marks" and "guide" sub-sub-menus.


Run the program
Source code : DemoMenuItem.java

Popup Menus. Text area window with popup menu -- to activate, move the cursor into the text area and then click on the right mouse button.


Run the program
Source code : DemoPopupMenu.java

Checkbox Menu Items. Menu bar with pull-down menu items (file, edit, options). The options bar has two items "fonts" and "others" which cascade into radio button and checkbox lists, respectively.


Run the program
Source code : DemoCheckBoxMenuItem.java

ToolBar with TextArea Window and ToolTips. Create tool bar with three (left, middle, right) image icons and a scrollable text area window. A text message is printed to the text area when an icon is clicked. (The action events are implemented as inner classes). Also check out tool tip text messages that popup when the cursor is positioned over an icon.


Run the program
Source code : DemoToolBar.java
WORKING WITH TIMERS AND PROGRESS BARS

Timers. This applet flashes the text label "Swing can flash!" in a variety of colors. The applet has control buttons to start, restart, and stop the flashing, and slider bars to contol the delay to firing events and time between color changes.


Run the program
Source code : DemoTimer.java

Progress Bar. This applet uses the Swing progress bar to indicate the progress of computation in the summation of numbers 1 through 100.


Run the program
Source code : DemoProgressBar.java

Progress Monitor. This applet computes the sum of numbers from one to a specified number. A progress bar pops up after the specified time (5 milliseconds in the code) to indicate progress in the calculation. (Note -- I think there is a small bug in the code).


Run the program
Source code : DemoProgressMonitor.java
WORKING WITH TABLES AND TREES

Simple Table Layout. This applet demonstrates how to make a simple table layout with a specified number of rows and columns. The table cells are empty and have no functionality -- useful, huh?


Run the program
Source code : DemoTableLayout.java

Populate Table with Data. This applet uses an array-of-arrays to populate the cells of a table. A second String array stores the olumn headings.


Run the program
Source code : DemoTableData.java
PROGRAMMING LOOK-AND-FEEL

Details coming soon ......


DEMONSTRATE CAPABILITIES OF JAVA 2D

Drawing Text on a Canvas. This applet creates a canvas with a white background, and displays "Let's dance all around the World!!" using a number of texture-paint types and font outlines. The applet uses affine transformations (i.e., the AffineTransform class) to concatenate transformations in 2D graphics (see java.awt.geom).


Run the program
Source code : DemoLetsDance.java

Clipping Operations. This applet demonstrates clipping along a circle positioned at the center of a canvas. The program clips the already clipped portion when the radio button "Clip Further" is selected. If the radio button "Clip" is selected again, the program clips the canvas as in the beginning. The program is an applet implementation of a standalone program presented in S. Pantham (1999).


Run the program
Source code : DemoClipping.java

Color Adjustment. This applet creates a canvas to display colors and a control panel to adjust the RGB and HSB values needed to create various shades of color. A slider is also provided for alpha value adjustment.

Note. When components with different colors overlap each other, the transparency of the foreground is the extent to which it allows the background color of pixels to be visible. This property of a color is called its alpha value.


Run the program
Source code : DemoColor.java

Texture Paint Patterns. Texture paint patterns are represented by the class TexturePaint in the package java.awt. A texture is specified by an image of type BufferedImage, which is subsequently copied within a shape to create a texture.

This applet demonstrates how texture paint patterns are created from "*.jpg" files. The applet window displays a sequence of textures as thumbnails. Clicking on a thumbnail will fill the canvas at the center of the window with the corresponding texture. Note. Pantham's implementation of this program is as a standalone Java program. The applet version is a bit more complicated because the texture patterns need to be downloaded over the net.


Run the program
Source code : DemoTexturePaint.java

Line Drawing. This applet demonstrates line drawing for a house, and includes a number of sliders for manipulation of the house position and geometry/shape. Take a look at this applet if you want to create a drawing canvas.


Run the program
Source code : DemoLine.java

2D Rectangles. This applet contains draws five rectangles on a canvas. The first rectangle does not contain a fill pattern. Rectangles two through five are filled with gradient and texture patterns and simple color styles. The rectangles overlap each other -- you can adjust the color-composite slider to alter the alpha value for compositing colors.


Run the program
Source code : DemoRectangles.java

Round-Cornered Rectangles. This applet draws a collection of round-cornered rectagles over a canvas. The program provides code that allows a user to interact with the rectangles using the mouse. More precisely, a user can click the mouse over any rectangle. The program recognizes the mouse clicks using API methods supported for checking whether a rectangle contains a point. It then uses a bounding box to draw small rectangular box indicating the box that has focus. Finally, a user can select a color from the list of colors in the combo box -- the focus rectangle will be filled in.


Run the program
Source code : DemoRoundRectangles.java

General Path Objects. General paths are shapes created by using combinations of lines, quadratic curves and cubic curves. You need to specify the coordinates of the starting, ending and control points of the primitives making up the general path. In Java 2D general paths are represeted by the class GeneralPath. Method exist for creating a path, and testing for edge intersection and point containment.

This applet displays eight general path objects ranging from very simple to complex shapes. The applet displays a control panel containing radio buttons for selection of a winding rule and push buttons to control the filling of shapes. It is adapted from Pantham S., Pure JFC Swing, 1999.


Run the program
Source code : DemoGeneralPath.java

Composite Shapes. Java supports composite shapes made up of areas of two or more existing shapes. Binary operations such as add, subtract, intersect and exclusive-or may be performed to create new shapes. This applet displays eight general path objects ranging from very simple to complex shapes. The applet displays a control panel containing radio buttons for selection of a winding rule and push buttons to control the filling of shapes.


Run the program
Source code : DemoCompositeShape.java

Platform Fonts. This applet retrieves and displays platform fonts. The fonts are displayed in the pull-down list of a combo box to allow selection of the font. The combo box is attached to the control panel. After a user has selected a new parameter, the program creates new font faces using these parameters. The font face is subsequently applied to the text shown in the display panel.


Run the program
Source code : DemoFont.java

Text Layout. This applet demonstrates how to use geometric (affine) transformations on text using the text layout support in Java 2D. The applet displays a text string and a set of sliders to translate, rotate, scale, and shear the text string.

Note. When a new affine transform is applied to text, it results in a new derived font (i.e., a new derived font results from a slider setting).


Run the program
Source code : DemoTextLayout1.java

Animation of Buffered Images. This applet animates a butterfly and from a java programming perspective is interesting in a couple of ways. First, the program uses a buffered image and affine transformations (scaling, translation, rotation) to transform the size and motion of the butterfly. The graphics animation works by storing the transformed image in a buffer and flipping it to the screen after applying the transformation to the buffered image. Thus, you see the butterfly moving around and changing size. Buttons are provided to start and stop the animation.

The second interest aspect of this program is the animation canvas, which runs as a separate thread of execution. The affine transformation is applied to the image that is stored in the buffered image.


Run the program
Source code : DemoAnimation.java
OTHER COOL APPLETS
Natasha's graph applet (check out the popup hints!)

Run the program
Source code : chart1.java


ACKNOWLEDGEMENTS

  1. Pantham S. (1999), Pure JFC Swing : A Code Intensive Premium Reference , SAMS Publishing, Indianapolis, Indiana 46290.
  2. Pantham S. (2000), Pure JFC 2D Graphics and Imaging , SAMS Publishing, Indianapolis, Indiana 46290.
  3. Walrath K. et al. (1999), Java Swing Tutorial , Sun Microsystems.


Developed in February 2001 by Mark Austin
Copyright © 2001, Department of Civil Engineering, University of Maryland