Chapter 20

Oooey GUI Was a Worm

In This Chapter

arrow Swinging into action

arrow Displaying an image

arrow Using buttons and text boxes

There’s a wonderful old joke about a circus acrobat jumping over mice. Unfortunately, I’d get sued for copyright infringement if I included the joke in this book.

Anyway, the joke is about starting small and working your way up to bigger things. That’s what you do when you read Beginning Programming with Java For Dummies, 3rd Edition.

Most of the programs in this book are text-based. A text-based program has no windows; no dialog boxes; nothing of that kind. With a text-based program, the user types characters in the Console view, and the program displays output in the same Console view.

These days, very few publicly available programs are text-based. Almost all programs use a GUI — a Graphical User Interface. So if you’ve read every word of this book up to now, you’re probably saying to yourself, “When am I going to find out how to create a GUI?”

Well, now’s the time! This chapter introduces you to the world of GUI programming in Java.

The Java Swing Classes

Java’s Swing classes create graphical objects on a computer screen. The objects can include buttons, icons, text fields, check boxes, and other good things that make windows so useful.

The name “Swing” isn’t an acronym. When the people at Sun Microsystems were first creating the code for these classes, one of the developers named it “Swing” because swing music was enjoying a nostalgic revival. And yes, in addition to String and Swing, the standard Java API has a Spring class. But that’s another story.

Actually, Java’s API has several sets of windowing components. An older set is called AWT — the Abstract Windowing Toolkit. But to use some of the Swing classes, you have to call on some of the old AWT classes. Go figure!

Showing an image on the screen

The program in Listing 20-1 displays a window on your computer screen. To see the window, look at Figure 20-1.

Listing 20-1: Creating a Window with an Image in It

import javax.swing.JFrame;

import javax.swing.ImageIcon;

import javax.swing.JLabel;

import java.awt.Container;

class ShowPicture {

    

    public static void main(String args[]) {

        JFrame frame = new JFrame();

        ImageIcon icon = new ImageIcon(“androidBook.jpg”);

        JLabel label = new JLabel(icon);

        

        frame.add(label);

        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

        frame.pack();

        frame.setVisible(true);

    }

}

technicalstuff.eps When you view Listing 20-1 in the Eclipse editor, you see a little yellow marker. A yellow marker represents a warning rather than an error, so you can ignore the warning and still run your code. If you hover over the marker, you see a tip about something called a serialVersionUID. A serialVersionUID is a number that helps Java avoid version conflicts when you send different copies of an object from one place to another. You can get rid of the warning by applying one of Eclipse’s quick fixes, but if you’re not fussy, don’t bother with these quick fixes.

The code in Listing 20-1 has very little logic of its own. Instead, this code pulls together a bunch of classes from the Java API.

Figure 20-1: What a nice window!

9780470371749-fg2001.eps

Back in Listing 17-3, I create an instance of the Purchase class with the line

Purchase onePurchase = new Purchase();

So in Listing 20-1, I do the same kind of thing. I create instances of the JFrame, ImageIcon, and JLabel classes with the following lines:

JFrame frame = new JFrame();

ImageIcon icon = new ImageIcon(“androidBook.jpg”);

JLabel label = new JLabel(icon);

Here’s some gossip about each of these lines:

check.png A JFrame is like a window (except that it’s called a JFrame, not a “window”). In Listing 20-1, the line

JFrame frame = new JFrame();

creates a JFrame object, but this line doesn’t display the JFrame object anywhere. (The displaying comes later in the code.)

remember.eps In this chapter, I use the words JFrame, frame, and window interchangeably. (Well, I use them almost interchangeably. You don’t have to think about any of the differences.)

check.png An ImageIcon object is a picture. At the root of the program’s project directory, I have a file named androidBook.jpg. That file contains the picture shown in Figure 20-1. So in Listing 20-1, the line

ImageIcon icon = new ImageIcon(“androidBook.jpg”);

creates an ImageIcon object — an icon containing the androidBook.jpg picture.

remember.eps For some reason that I’ll never understand, you may not want to use my androidBook.jpg image file when you run Listing 20-1. You can use almost any .gif, .jpg, or .png file in place of my (lovely) Android book cover image. To do so, drag your own image file to Eclipse’s Package Explorer. (Drag it to the root of this example’s project folder.) Then, in Eclipse’s editor, change the name androidBook.jpg to your own image file’s name. That’s it!

check.png I need a place to put the icon. I can put it on something called a JLabel. So in Listing 20-1, the line

JLabel label = new JLabel(icon);

creates a JLabel object and puts the androidBook.jpg icon on the new label’s face.

If you read the previous bullets, you may get a false impression. The wording may suggest that the use of each component (JFrame, ImageIcon, JLabel, and so on) is a logical extension of what you already know. “Where do you put an ImageIcon? Well of course, you put it on a JLabel.” When you’ve worked long and hard with Java’s Swing components, all these things become natural to you. But until then, you look everything up in Java’s API documentation.

remember.eps You never need to memorize the names or features of Java’s API classes. Instead, you keep Java’s API documentation handy. When you need to know about a class, you look it up in the documentation. If you need a certain class often enough, you’ll remember its features. For classes that you don’t use often, you always have the docs.

For tips on using Java’s API documentation, see the Appendix on this book’s website — http://allmycode.com/BeginProg3. To find gobs of sample Java code, visit some of the websites listed in Chapter 21.

Just another class

What is a JFrame? Like any other class, a JFrame has several parts. For a simplified view of some of these parts, see Figure 20-2.

Like the String in Figure 18-6 in Chapter 18, each object formed from the JFrame class has both data parts and method parts. The data parts include the frame’s height and width. The method parts include add, ­setDefaultCloseOperation, pack, and setVisible. All told, the JFrame class has about 320 methods.

Figure 20-2: A simplified depiction of the JFrame class.

9780470371749-fg2002.tif

For technical reasons too burdensome for this book, you can’t use dots to refer to a frame’s height or width. But you can call many JFrame methods with those infamous dots. In Listing 20-1, I call the frame’s methods by ­writing add(label), frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE), frame.pack(), and frame.setVisible(true).

Here’s the scoop on the JFrame methods in Listing 20-1:

check.png The call frame.add(label) plops the label onto the frame. The label displays my androidBook.jpg picture, so this call makes the picture appear on the frame.

check.png A call to frame.setDefaultCloseOperation tells Java what to do when you try to close the frame. (In Windows, you click the ‘x’ in the upper-right-hand corner by the title bar. On a Mac, the ‘x’ is in the frame’s upper-left corner.) For a frame that’s part of a larger application, you may want the frame to disappear when you click the ‘x’, but you probably don’t want the application to stop running.

But in Listing 20-1, the frame is the entire application — the whole ­enchilada. So when you click the ‘x’, you want the Java virtual machine to shut itself down. To make this happen, you call the ­setDefaultCloseOperation method with parameter ­ JFrame.EXIT_ON_CLOSE. The other alternatives are as follows:

JFrame.HIDE_ON_CLOSE: The frame disappears, but it still exists in the computer’s memory.

JFrame.DISPOSE_ON_CLOSE: The frame disappears and no longer exists in the computer’s memory.

JFrame.DO_NOTHING_ON_CLOSE: The frame still appears, still exists, and still does everything it did before you clicked the ‘x.’ Nothing happens when you click ‘x.’ So with this DO_NOTHING_ON_CLOSE option, you can become very confused.

warning_bomb.eps If you don’t call setDefaultCloseOperation, then Java automatically chooses the HIDE_ON_CLOSE option. When you click the ‘x’, the frame disappears, but the Java program keeps running. Of course, with no visible frame, the running of Listing 20-1 doesn’t do much. The only noticeable effect of the run is your development environment’s behavior. With Eclipse, the little square in the Console view’s toolbar retains its bright red color. When you hover over the square, you see the Terminate tooltip. So to end the Java program’s run (and to return the square to its washed-out reddish-grey hue) simply click this little square.

check.png A frame’s pack method shrink-wraps the frame around whatever has been added to the frame’s content pane. Without calling pack, the frame can be much bigger or much smaller than is necessary.

Unfortunately, the default is to make a frame much smaller than necessary. If, in Listing 20-1, you forget to call frame.pack, you get the tiny frame shown in Figure 20-3. Sure, you can enlarge the frame by dragging the frame’s edges with your mouse. But why should you have to do that? Just call frame.pack instead.

check.png Calling setVisible(true) makes the frame appear on your screen. If you forget to call setVisible(true) (and I often do), when you run the code in Listing 20-1, you’ll see nothing on your screen. It’s always so disconcerting until you figure out what you did wrong.

Figure 20-3: A frame that hasn’t been packed.

9780470371749-fg2003.eps

Using Eclipse’s WindowBuilder

A GUI program is nothing special. Every GUI program is simply a Java source file (or more likely, several Java source files) like the files in this book’s code listings. But GUI programs have two interesting characteristics:

check.png GUI programs typically contain lots of Java code.

Much of this code differs very little from one GUI program to another.

check.png GUI programs involve visual elements.

The best way to describe visual elements is to “draw” them. Describing them with Java source code can be slow an unintuitive.

So to make your GUI life easier, you can add WindowBuilder to the Eclipse IDE. With WindowBuilder, you describe your program visually. WindowBuilder automatically turns your visual description into real Java source code.

technicalstuff.eps Some websites use the name WindowBuilder Pro. As far as I know, WindowBuilder Pro is another name for plain old WindowBuilder.

Installing WindowBuilder

Eclipse has its own elaborate facility for incorporating new functionality. An Eclipse tool is called an Eclipse plugin. When you first install Eclipse, you get many plugins by default. Then, to enhance Eclipse’s power, you can install many additional plugins.

Eclipse’s WindowBuilder plugin facilitates the creation of GUI applications. Here’s how you install WindowBuilder:

1. In Eclipse’s main menu, choose HelpInstall New Software.

An Install dialog opens.

2. In the Install dialog, click the Add button.

An Add Repository dialog opens.

3. In the Add Repository dialog, type a name (hopefully a name that reminds you of WindowBuilder) and a Location URL (see Figure 20-4).

Figure 20-4: Eclipse’s Add Repository dialog.

9780470371749-fg2004.eps

The Location URL points to a place on the web where the WindowBuilder plugin is available for download. In early 2012, the correct URL is http:// download.eclipse.org/windowbuilder/WB/integration/3.8/ and http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7 works as well. Unfortunately, I can’t guarantee that the same URLs will work when you read this book. But if you visit www.eclipse.org/windowbuilder in your web browser and do some poking around, you’ll probably find the most recent URL. Look for something called the Update Site URL.

warning_bomb.eps The Add Repository dialog’s Location field isn’t like your web browser’s Address field. You can’t abbreviate the URL by omitting the http:// part.

4. Click OK to close the Add Repository dialog.

At this point in your journey, the Install dialog displays a list of plugins that are available on your Location URL’s server (see Figure 20-5). If you’re like me, you want everything.

Figure 20-5: The Install dialog.

9780470371749-fg2005.eps

5. Click the Select All button and then click Next.

At this point, Eclipse asks for your acceptance of the license agreement’s terms (which include no mention of your first-born child).

6. Accept the agreement and follow any other instructions that Eclipse throws at you.

After some clicking and agreeing, your download begins. The plugin installs itself automatically into Eclipse. When the download is finished and you restart Eclipse, you have full use of the Eclipse WindowBuilder plugin.

Creating a GUI class

There’s a wise old saying, “A picture is worth 70 words.” And if you count things like java.awt.EventQueue as three separate words, the same picture is worth 80 words. In this section, you create a picture from which Eclipse builds an 80-word Java program.

1. Follow the instructions in the previous section (the “Installing WindowBuilder” section).

2. Create a new Java project.

If you’re following my instructions to the letter, name the project WindowBuilderProject.

3. Select the new project’s branch in Eclipse’s Package Explorer.

4. In Eclipse’s main menu, choose FileNewOther.

The Select A Wizard dialog box appears.

5. In the Select A Wizard dialog box’s tree, expand the WindowBuilder branch.

6. Within the WindowBuilder branch, expand the Swing Designer branch.

Java’s Swing classes create graphical objects on a computer screen. The objects can include buttons, icons, text fields, check boxes, and other good things that make windows so useful.

7. Within the Swing Designer branch, double-click the JFrame item.

A New JFrame dialog box appears, as shown in Figure 20-6.

Figure 20-6: The New JFrame dialog box.

9780470371749-fg2006.eps

8. In the dialog box’s Name field, type a name for your new Java class.

If you’re following my instructions faithfully, name the class MyFrame.

9. Remove the check mark from the box labeled Use Advanced Template For Generate JFrame.

The label’s wording is very strange. I didn’t create the wording, so don’t blame me! If the creators of WindowBuilder have replaced “for generate” with “to generate” by the time you read this book, then remove the check mark from that sensibly labeled check box.

warning_bomb.eps If you perform Steps 8 and 9 out of order, you may get unexpected results. For some odd reason, Eclipse puts a check mark in the Use Advanced Template check box when you enter anything (even a single character) in the Name field. With any luck, this bizarre behavior will be fixed by the time you install Eclipse.

10. Click the Finish button to dismiss the New JFrame dialog box.

Eclipse’s workbench reappears. Your new MyFrame.java file appears in the editor.

Running your bare-bones GUI class

In the previous section, you use WindowBuilder to create a brand-new Java class. When you run the new class’s code, you see the stuff in Figure 20-7. You see a window (more precisely, a JFrame instance) with nothing inside it.

Figure 20-7: An empty JFrame.

9780470371749-fg2007.eps

The fact that this JFrame contains no images, no buttons, no text fields — no nothing — comes from the way WindowBuilder creates your new class. WindowBuilder populates the class with a minimum amount of code. That way, the new class is a blank slate — an empty shell to which you add buttons, text fields, or other useful components.

The next section describes the Java code that creates the display in Figure 20-7.

Show me the code

Listing 20-2 contains the code that WindowBuilder generates automatically. When you run the code, you get the rather bland display in Figure 20-7.

Listing 20-2: WindowBuilder creates a minimal GUI application

import java.awt.EventQueue;

import javax.swing.JFrame;

public class MyFrame extends JFrame {

  /**

   * Launch the application.

   */

  public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {

      public void run() {

        try {

          MyFrame frame = new MyFrame();

          frame.setVisible(true);

        } catch (Exception e) {

          e.printStackTrace();

        }

      }

    });

  }

  /**

   * Create the frame.

   */

  public MyFrame() {

    setBounds(100, 100, 450, 300);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

}

Listing 20-2 contains several features that tend to confuse new programmers. But at its core, Listing 20-2 does the same thing as the simpler Listing 20-3.

Listing 20-3: The essence of the code in Listing 20-2

import javax.swing.JFrame;

class ShowEmptyFrame {

  public static void main(String[] args) {

    JFrame frame = new JFrame();

    

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setBounds(100, 100, 450, 300);

    frame.setVisible(true);

  }

}

Like its intricate predecessor, Listing 20-3 displays the empty frame shown in Figure 20-7. To help display the frame, Listing 20-3 calls the frame’s ­setDefaultCloseOperation and setVisible methods.

The only brand-new feature in Listing 20-3 is the call to the frame’s ­setBounds method. Calling setBounds(100, 100, 450, 300) creates a frame with the following measurements:

check.png The frame’s upper-left corner is 100 pixels from the left edge of the screen.

check.png The frame’s upper-left corner is 100 pixels from the top of the screen.

check.png The frame is 450 pixels wide.

check.png The frame is 300 pixels high.

Some details about the code

You can use WindowBuilder without understanding any of the subtleties in Listing 20-2. But if full comprehension is your goal for Listing 20-2, you can start by reading this section.

In Listing 17-3 in Chapter 17, I create an instance of the Purchase class with the line

Purchase onePurchase = new Purchase();

The code in Listing 20-2 does the same kind of thing. In Listing 20-2, Window-Builder creates an instance of the MyFrame class with the following line:

MyFrame frame = new MyFrame();

Compare Figure 17-4 in Chapter 17 with this chapter’s Figure 20-8.

Figure 20-8: An object created from the MyFrame class.

9780470371749-fg2008.tif

In both figures, a new SomethingOrOther() constructor call creates an object from an existing class.

check.png In Chapter 17, I create an instance of my Purchase class.

This object represents an actual purchase (with a purchase amount, a tax, and so on).

check.png In this chapter, I create an instance of the MyFrame class (the class in Listing 20-2).

This object represents a frame on the computer screen (a frame with borders, a minimize button, and so on). In a more complicated application — an app that displays several frames — the code might create several objects from a class such as MyFrame (see Figure 20-9).

Extending a class

In Listing 20-2, the words extends JFrame are particularly important. When you see Java’s extends keyword, imagine replacing that keyword with the phrase “is a kind of.”

public class MyFrame is a kind of JFrame {

When you type MyFrame extends JFrame, you declare that your new MyFrame class has all the methods and other things that are built into Java’s own JFrame class, and possibly more. For example, a JFrame instance has setDefaultCloseOperation, setBounds and setVisible methods, so every new MyFrame instance has setDefaultCloseOperation, setBounds and setVisible methods (see Figure 20-10).

Figure 20-9: Creating three objects from the MyFrame class.

9780470371749-fg2009.tif

Figure 20-10: A MyFrame instance has many methods.

9780470371749-fg2010.tif

And the best part is, you get all of the JFrame methods for free. The MyFrame class’s code doesn’t need declarations for methods, such as ­setDefaultCloseOperation, setBounds, and setVisible (see Listing 20-2). The only declarations in the MyFrame class’s code are for brand-new methods — methods that aren’t already declared in the JFrame class’s code. It’s as if Listing 20-2 contained the following information:

public class MyFrame is a kind of JFrame {

    And in addition to what’s in JFrame, MyFrame also has

    public static void main(String[] args) {

        // Etc.

    }

    And in addition what’s in JFrame, MyFrame also has

    public MyFrame() {

        // Etc.

    }

}

The extends keyword adds a very important idea to Java programming — the notion of inheritance. In Listing 20-2, the newly created MyFrame class inherits the methods (and other things) that are declared in the existing JFrame class. Inheritance is a pivotal feature of an object-oriented programming language.

Java class, instantiate thyself!

The example in Chapter 17 consists of two Java classes — one class that defines what it means to be a Purchase (Listing 17-2), and another class that creates an object from the Purchase class (Listing 17-3). The second class uses its object to calculate things about a purchase. In other words, Listing 17-2 says “this is what a purchase looks like,” and Listing 17-3 says “create a purchase and the do these things with the purchase.”

But the code in Listing 20-2 has an interesting quirk. The code plays two roles. First, the code defines what it means to be a MyFrame:

public class MyFrame extends JFrame {

The code also creates an object from the MyFrame class:

public static void main(String[] args) {

    MyFrame frame = new MyFrame();

I illustrate the situation in Figure 20-11.

Figure 20-11: The MyFrame class ­creates a MyFrame object.

9780470371749-fg2011.tif

The code in Listing 20-2 creates an instance of itself. As strange as it seems, this self-replicating behavior is a common Java programming idiom. You take a class that defines something useful (such as a MyFrame), and then you plunk a main method inside the class’s code.

For me, the whole business is weird. You wouldn’t create a class that describes both checking accounts and race horses, so why does WindowBuilder create a class that describes both a frame and a program’s main flow of control? My only guess is that Java programmers think of main methods as oddballs in object-oriented programming. For programmers, a main method is a necessary evil — the single step that begins a thousand-mile journey.

How to avoid traffic jams

If Marcel Proust had been a computer programmer, he would have written the main method in Listing 20-2. This method is a study in the use of braces, parentheses, and semicolons. To get the main method in Listing 20-2, you start with two innocent statements:

MyFrame frame = new MyFrame();

frame.setVisible(true);

You put those statements inside a try-catch statement (whatever that is). The try-catch statement is inside a method named run, which is inside a new Runnable() constructor call, which is in turn inside an EventQueue.invokeLater method call. Whew!

I don’t dare attempt to describe the main method’s code in detail. (John Wiley & Sons, Inc. would have to kill too many trees.) Instead, I describe the reason behind the code — what’s deficient in this chapter’s odd-numbered listings and (roughly) why Listing 20-2 is better.

A Java program is multithreaded, which means that during a Java program’s run, several things happen at once. While part of your code is calculating rent payments, another part of your code draws a frame on the screen, and yet another part of Java’s virtual machine listens for the user’s key presses and mouse clicks.

With all that stuff happening at once, you might experience bottlenecks. You might even experience deadlocks — situations in which two parts of your code play a virtual game of chicken with one another. “I won’t run until you run,” says one part of your code to another. “Well, then we’re stuck, because I won’t run until you run,” says the other part to the first part. Your Java program freezes, and your program’s window is completely unresponsive.

To avoid the possibility of such a standoff, WindowBuilder creates the main method in Listing 20-2. This main method carefully funnels all frame-related business to one event-dispatching thread. Think of the event-dispatching thread as a traffic cop. One part of your code says, “I want to maximize the frame.” Another part of your code says, “I want to change the frame’s color.” With the main method in Listing 20-2, one part asks the event-dispatching thread to “maximize the frame when you have the opportunity to do so.” And the other part asks the same event-dispatching thread to “change the frame’s color when you can.” The event-dispatching thread controls the workflow and keeps traffic moving along.

Now there’s comforting news. The main method in Listing 20-2 is boilerplate code. If your GUI application isn’t too fancy, you can simply copy this main method into your application’s .java file. (Remember to change MyFrame to whatever name you’ve given to your Java class.) And if you create your program using WindowBuilder, the WindowBuilder tool writes the main method for you. No additional tinkering is required.

Adding Stuff to Your Frame

I like empty spaces. When I lived on my own right out of college, my apartment had no pictures on the walls. I didn’t want to stare at the same works of art day after day. I preferred to fill in the plain white spaces with images from my own imagination. So for me, the empty frame in Figure 20-7 is soothing.

But if Figure 20-7 isn’t acquired by New York’s Museum of Modern Art, the frame is quite useless. (By the way, I’m still waiting to hear back from the museum’s curator.) When you create a high-powered GUI program, you start by creating a frame with buttons and other widgets. Then you add methods to respond to keystrokes, button clicks, and other such things.

The next section contains some code to respond to a user’s button clicks. But in this section, you use WindowBuilder to display a button and a text field:

1. Follow the instructions in this chapter’s earlier “Creating a GUI class” section.

2. With MyFrame.java in the editor, look for two tabs at the bottom of the editor area.

The labels on the tabs are Source and Design. The Source tab displays Java code (the stuff in Listing 20-2).

3. Select the Design tab.

The Design tab displays a preview of the frame and a palette full of things that you can add to the frame (see Figure 20-12).

Figure 20-12: The Design tab.

9780470371749-fg2012.tif

tip.eps You can quickly enlarge the Design area by double-clicking the MyFrame.java tab at the top of the editor.

4. In the Layouts section of the Palette, click the FlowLayout item.

In response, the FlowLayout item appears to be pressed down (see Figure 20-13).

Figure 20-13: Preparing to add a FlowLayout to your frame.

9780470371749-fg2013.tif

A FlowLayout arranges objects in a row, one right after another across the frame. After filling an entire row with objects, Java places additional objects on a second row (or a third, fourth, or fifth row, if necessary).

technicalstuff.eps By default, your frame has a BorderLayout. In a BorderLayout, items such as text fields and buttons land in one of five regions — the NORTH, SOUTH, EAST, WEST, and CENTER regions. But you can apply any item in the palette’s Layouts section to your frame. For example, with an AbsoluteLayout (also known as a null layout), you can drag buttons and other components to any location on the frame. With a GridLayout, you put things into cells in a table. To learn more, put any of the palette’s layouts on your frame and watch what happens.

5. Hover your mouse pointer over the preview of your frame.

Again, see Figure 20-13.

6. With your mouse pointer still hovering over the frame’s preview, click the mouse.

At this point, WindowBuilder’s response is a big letdown. The Design tab returns to its original look with nothing special in the frame and with none of the palette’s items pressed down.

tip.eps To change your mind between Steps 5 and 6 (deciding against adding a FlowLayout to the frame), press Escape.

remember.eps As you’d do when following any long sequence of instructions, pause frequently to save your work in progress. In Eclipse’s main menu, choose File⇒Save.

7. Look for two items in the Components section of the Palette — the JTextField item and the JButton item (see Figure 20-13).

Java’s JTextField class describes a white box (commonly known as a text field) in which the user types a line of text. The JButton class describes one of those clickable things that we all know and love. The frame in Figure 20-14 contains an empty JTextField component, and a JButton component with the words New button on its face.

Figure 20-14: Your frame contains a text field and a ­button.

9780470371749-fg2014.tif

You can make your frame look like the frame in Figure 20-14:

8. Repeat Steps 4 through 6, this time adding a JTextField to your frame.

9. Repeat Steps 4 through 6, this time adding a JButton to your frame.

The resulting preview frame is in Figure 20-14.

Having added some widgets to the frame, you can make some refinements.

10. With your mouse, select the JTextField in the preview of the frame (see Figure 20-15).

tip.eps You can also select a component by clicking the component’s name in the Components pane. You find the Components pane in the upper-right corner of the editor area.

Figure 20-15: Selecting the JTextField component.

9780470371749-fg2015.tif

11. Look for the Properties pane in lower-left corner of the editor area.

The Properties pane displays characteristics of the currently selected component (see Figure 20-16).

12. Type some stuff in the Properties pane’s text row (see Figure 20-17).

13. Click your mouse anywhere outside of the Property pane’s text row (preferably at some neutral point inside the Editor area).

Now the JTextField component in the frame’s preview contains your text (see Figure 20-18). But as you can see, the JTextField component may not be wide enough.

Figure 20-16: The Properties pane displays the JTextField component’s properties.

9780470371749-fg2016.tif

Figure 20-17: Typing text into one of the Properties pane’s rows.

9780470371749-fg2017.tif

Figure 20-18: Text in the text field.

9780470371749-fg2018.eps

14. Again, select the JTextField component in the preview of the frame and then increase the number in the Columns row of the Properties pane.

The width of the JTextField component increases accordingly.

A few more refinements are in order:

15. Select the JButton component and use the Properties pane to change the component’s text.

In Figure 20-19, I change the text to the word Capitalize.

Figure 20-19: Changing the text on the face of the button.

9780470371749-fg2019.tif

16. Select the entire frame by clicking somewhere on the frame’s border and then use the Properties pane to change the frame’s Title property.

In Figure 20-19, the frame’s title is Handy Capitalization Service.

As you follow this section’s steps, WindowBuilder modifies your project’s Java code. Having followed this section’s steps, you can run the project in the usual way (by choosing Run⇒Run As⇒Java Application). But when the project runs, the frame doesn’t do anything. When you click the button on the frame, nothing happens. When you type in the text field, nothing happens. What a waste!

In the next section, you get the button to do something.

Taking Action

The program that you create in this chapter is approximately 50 lines long. But up to this point in the chapter, you don’t type a single line of code! That’s about to change because, in this section’s instructions, you make a button respond to a mouse click. And, yes, you do this by typing a single line of code!

tip.eps You can write Android apps (for mobile phones and tablet devices) in Java, and using the App Inventor tool you can write some complete Android programs without writing any code at all (not even a single line). I happen to know about an excellent book in which 2 out of 24 chapters cover App Inventor. It’s Android Application Development All-in-One For Dummies (Wiley) by Barry Burd. (Oh, no! Yet another shameless plug!)

1. Follow the instructions in this chapter’s earlier “Adding Stuff to Your Frame” section.

As a result, you have a frame containing a text field (a JTextField component) and a button (a JButton component). You’re using the Design tab — a tool belonging to Eclipse’s WindowBuilder.

2. In the preview of the frame (or in the Components pane), right-click the JButton component; as usual, Mac users Control-click the JButton component.

3. In the resulting context menu, choose Add Event Handler.

I’m proud that I figured out how to create Figure 20-20. So please have a look at it.

Figure 20-20: Cascading context menus.

9780470371749-fg2020.eps

4. In the resulting context submenu, choose action.

5. In the resulting context sub-submenu, choose actionPerformed (see Figure 20-20).

When you click actionPerformed, Eclipse takes you to the Java code that WindowBuilder has created (see Figure 20-21).

Figure 20-21: The code that Window-Builder built.

9780470371749-fg2021.tif

6. In the Java code, look for the name of the JTextField component.

In Figure 20-21, the component’s name is txtTypeYourText. WindowBuilder creates a name for each of your components. By default, your first empty text field is named textField. Your second empty text field is named textField_1. A text field containing the text Hello! How are you? is named txtHelloHowAre. I don’t know all the naming rules, but the ones that I know seem to make sense.

7. Type the following line of code inside the actionPerformed method:

nameOfYourJTextComponent.setText

  (nameOfYourJTextComponent.getText().toUpperCase());

For a text field whose name is txtTypeYourText, the added line of code is shown in Figure 20-22.

Figure 20-22: Adding code to the actionPerformed method.

9780470371749-fg2022.tif

8. Save and run your program!

When you run this section’s program, you see something like the screen shots in Figures 20-23, 20-24, and 20-25. Et voilà! When you click the button, Java capitalizes your text!

Figure 20-23: A brand-new frame.

9780470371749-fg2023.eps

Figure 20-24: The user types in the text box.

9780470371749-fg2024.eps

Figure 20-25: Clicking the button capitalizes the text in the text box.

9780470371749-fg2025.eps

For your reading pleasure, I’ve pasted all the code for this section’s example into Listing 20-4. The only statement that you type yourself is in bold near the end of the listing.

Listing 20-4: Capitalism in Action

import java.awt.EventQueue;

import javax.swing.JFrame;

import java.awt.FlowLayout;

import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

public class MyFrame extends JFrame {

  private JTextField txtTypeYourText;

  /**

   * Launch the application.

   */

  public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {

      public void run() {

        try {

          MyFrame frame = new MyFrame();

          frame.setVisible(true);

        } catch (Exception e) {

          e.printStackTrace();

        }

      }

    });

  }

  /**

   * Create the frame.

   */

  public MyFrame() {

    setTitle(“Handy Capitalization Service”);

    setBounds(100, 100, 450, 300);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

    

    txtTypeYourText = new JTextField();

    txtTypeYourText.setText(“Type your text here.”);

    getContentPane().add(txtTypeYourText);

    txtTypeYourText.setColumns(20);

    

    JButton btnNewButton = new JButton(“Capitalize”);

    btnNewButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        txtTypeYourText.setText

          (txtTypeYourText.getText().toUpperCase());

      }

    });

    getContentPane().add(btnNewButton);

  }

}

Want to read more? I have a whole chapter about it in Java For Dummies, 5th Edition (written by yours truly and published by John Wiley & Sons, Inc.).