CS 3230 - Lab 6

GUI Hello World

Here, you're going to make a GUI version of "Hello World", with a couple of added extras to help familiarize you with the Java GUI classes.

I'm kind of babying you guys here because this is new territory, so plan on things getting tougher in the the following labs.

Specifications

Picture worth a thousand words, here's the lab you're going to make:

To accomplish this lab, you will need to make two classes, Lab6, derived from JFrame and DrawPanel derived from JPanel. Put both classes in a file called Lab6.java.

Lab6 class (extends JFrame)

This class will need two methods: main and a constructor.

main method (public static void)

Constructor

DrawPanel class (extends JPanel)

You will need to write a custom panel class that includes one variable: an Image object, and two methods: a constructor and a paintComponent() method.

Image Variable

Declare a private variable of type Image. You will be using it in both of the other methods.

Constructor

Within a try...catch block, call ImageIO.read to read a GIF or JPEG file and put it into the private, Image object. (Hint: Look at ImageExample.java.)

paintComponent() method

Questions and Answers

Where do I get the image of the earth you used?

Right here. Alternatively, you can find your own...

I'm getting lots of "cannot resolve symbol" errors.

Technically, not a question, but I'll answer it anyway: Are you importing all of the following packages?

import javax.swing.*;
import javax.imageio.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.*;

Is the DrawPanel supposed to be an inner class?

No, it should be a seperate, standalone class that is declared in the same file below the Lab6 class.

How do I center the text in the label?

Use this constructor of the JLabel class. In a nutshell, you do it like this:

... new JLabel("Hello World!", JLabel.CENTER)

Why doesn't it insert a newline when I put "\n"?

Some of you may be trying to display the text "DON'T PANIC" by using a newline between the words like so: "DON'T\nPANIC". The "\n" escape is a convenience afforded you by the command-line environment; it does not work in the GUI world when you are drawing strings onto a Panel.

To get the two words to display one beneath the other, you will need to make two (2) calls to Graphics.drawString(), giving it different x,y coordinates each time (or at least different y coordinates each time).

What about my Application Project?

You can start making some headway today on your application project by coding the frame that will be displayed when the user first starts the program. You might even plop in a few controls.