JAVA SWING AND JAVA 2D

PART 1. SIMPLE SWING APPLETS PROGRAM AND SOURCE CODE
Program 01. 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
Program 02. 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
PART 2. WORKING WITH IMAGES
Program 03. 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
PART 3. WORKING WITH LAYOUT MANAGERS

Program 04. 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

Program 05. 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

Program 06. 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

Program 07. 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).

The 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

Program 08. 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
PART 4. DEMONSTRATE HANDLING OF EVENTS
Program 09. 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
Program 10. MouseMotion 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
Program 11. ActionEvent 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
PART 5. BASIC SWING COMPONENTS
Program 12. Button Component

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

Program 13. Slider Component

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

Program 14. Scroll Pane Component

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

Program 15. Tabbed Pane Component

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

Program 16. Scrollbars Component

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

Program 17. Text Field and Text Area Components

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

Program 18. Color Chooser Component

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
PART 5. WORKING WITH MENUS AND TOOLBARS

Program 19. Menubar Component

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


Run the program
Source code: DemoMenuBar.java

Program 20. 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

Program 21. 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

Program 22. 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

Program 23. 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
PART 6. WORKING WITH TIMERS AND PROGRESS BARS

Program 24. 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

Program 25. 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

Program 26. 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
PART 7. WORKING WITH TABLES AND TREES

Program 27. 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

Program 28. 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
PART 8. WORKING WITH JAVA 2D

Program 29. 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

Program 30. 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

Program 31. Working with 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

Program 32. 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

Program 33. 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

Program 34. 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

Program 35. 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

Program 36. 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 represented 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

Program 37. 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

Program 38. 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

Program 39. 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

Program 40. 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
PART 9. WORKING WITH AFFINE TRANSFORMS

Program 41. Simple Grid Application

This application creates a simple GUI with a panel. An affine transformation repositions and flips the coordinate system from the top left-hand corner to the lower left-hand corner adjusted by a border buffer.

Dots along the x- and y-axes are drawn in red. Otherwise the grid dots are drawn in black.

If you resize the window, the grid will automatically redraw to fill the screen.


Source code: DemoSimpleGrid.java
GraphicsGrid.java
GraphicsOperation.java
SimpleScreen.java

Program 42. Animate Hierarchy of Car Movement and Windmills

This application creates a panel that displays a two-dimensional animation that is constructed using hierarchical modeling.

In this scenario a cart rolls down a road while a sun shines and three windmills turn in the background. This class also contains a main() routine that simply opens a window that displays the animation.



Source code: HierarchicalModeling2D.java

Program 43. Scene of Compound Shapes

In this application we display a scene of compound shapes.

You can mouseover the shapes and they will be highlighted.



Zipped source code: compound-shapes.zip

REFERENCES

  1. Horstmann C., Object-Oriented Design and Patterns, John-Wiley and Sons, 2006.
  2. Pantham S. (1999), Pure JFC Swing : A Code Intensive Premium Reference , SAMS Publishing, Indianapolis, Indiana 46290.
  3. Pantham S. (2000), Pure JFC 2D Graphics and Imaging , SAMS Publishing, Indianapolis, Indiana 46290.
  4. Walrath K. et al. (1999), Java Swing Tutorial , Sun Microsystems.


Last modified: April 2012 by Mark Austin
Copyright © 2012, Department of Civil and Environmental Engineering, University of Maryland