Introduction to Java GUI and Graphics
Java MACUL Workshop—Java GUIs
Code examples are modifications of programs taken from Lewis & Loftus's Java Software Solutions, and from Cay Horstman's JustJava.
- Java's window-based user interface
- Frames.
- SimpleFrameTest.java
- CenteredFrame.java. Put icon.gif in same directory as CenteredFrame.java.
Panels.
- NotHelloWorld.java
- Exercise: Modify NotHelloWorld to print 5 rows of a 5 x 5 multiplication table. You'll need several calls to drawString.
- Panels are containers! See NestedPanels.java.
- Simple 2D graphics
- Lines, rectangles, ovals, arcs, color.
- Snowman.java
- Bullseye.java
- DrawTest.java (optional: demonstrates the Graphics2D library)
- Exercise: modify Bullseye so that the circles are not centered, but instead their right edges are all aligned.
- GUI widgets: buttons, checkboxes, radio buttons, labels
- Layout Manager (optional): LayoutDemo, IntroPanel, FlowPanel, BorderPanel, GridPanel, BoxPanel
- JLabels and JButtons, PushCounter.java and PushCounterPanel.java.
- Exercise: Modify PushCounter so that it has two buttons and two labels. The buttons should be labeled "Bush" and "Gore". The labels should show the number of "votes" having been made for Bush and for Gore.
- JTextFields, Fahrenheit.java and FahrenheitPanel.java.
- RadioButtons (optional), QuoteOptions.java and QuoteOptionsPanel.java.
- The Event-driven programming paradigm
- Program state
- Rendering the state
- Events and Event generators
- Event listeners (handlers), registering event listeners
- Listeners change program state
- The loop: draw the state, wait, event occurs, listener invoked, state changed, call for redraw
- Interacting with the mouse: MouseTest.java. (This code uses templates, a Java 5 technique. You will need JDK1.5 or later to compile this.)
- Animation
- Timer object, DemoAnimation.java.
- Exercise: First, modify the animation so that the object is randomly colored. There is code for generating a random color below. After that, add another button that, when clicked, changes the color of the object to a random color. You'll have to change the paintComponent method so that it uses a variable, rather than a constant to set the foreground color. Finally, add a second object, in a different (random) color that moves differently.
Random generator = new Random();
Color myColor = new Color(generator.nextInt(256),generator.nextInt(256),generator.nextInt(256));
- Converting applications into applets. The JApplet object takes the place of the JFrame. The insertion of the top-most panel is now into the JApplet, rather than the frame. This is done in the applet's init() method. You need not provide a paint() method for the applet, because the default behavior will be to invoke the paintComponent method of the panel that has been inserted into the applet's contentPane.
- See DemoAnimationApplet.java, DemoAnimationApplet.html.
- Exercise: Convert the MouseTest application into an applet.
JustJava Code Examples