Creating Your Own Component

An advantage of OOP is the capability to reuse classes in different projects. For the next project, you create a special panel component that you can reuse in other Java programs. The component, ClockPanel, displays the current date and time in a manner similar to the ClockTalk project from Hour 7, “Using Conditional Tests to Make Decisions.”

The first step in creating your own user interface component is to decide the existing component from which to inherit. The ClockPanel component is a subclass of JPanel.

The ClockPanel class is defined in Listing 13.3. This class represents panel components that include a label displaying the current date and time. Enter the text from Listing 13.3 into a new empty Java file and save the file.

Listing 13.3. The Full Text of ClockPanel.java


 1: import javax.swing.*;
 2: import java.awt.*;
 3: import java.util.*;
 4:
 5: public class ClockPanel extends JPanel {
 6:     public ClockPanel() {
 7:         super();
 8:         String currentTime = getTime();
 9:         JLabel time = new JLabel("Time: ");
10:         JLabel current = new JLabel(currentTime);
11:         add(time);
12:         add(current);
13:     }
14:
15:     final String getTime() {
16:         String time;
17:         // get current time and date
18:         Calendar now = Calendar.getInstance();
19:         int hour = now.get(Calendar.HOUR_OF_DAY);
20:         int minute = now.get(Calendar.MINUTE);
21:         int month = now.get(Calendar.MONTH) + 1;
22:         int day = now.get(Calendar.DAY_OF_MONTH);
23:         int year = now.get(Calendar.YEAR);
24:
25:         String monthName = "";
26:         switch (month) {
27:             case (1):
28:                 monthName = "January";
29:                 break;
30:             case (2):
31:                 monthName = "February";
32:                 break;
33:             case (3):
34:                 monthName = "March";
35:                 break;
36:             case (4):
37:                 monthName = "April";
38:                 break;
39:             case (5):
40:                 monthName = "May";
41:                 break;
42:             case (6):
43:                 monthName = "June";
44:                 break;
45:             case (7):
46:                 monthName = "July";
47:                 break;
48:             case (8):
49:                 monthName = "August";
50:                 break;
51:             case (9):
52:                 monthName = "September";
53:                 break;
54:             case (10):
55:                 monthName = "October";
56:                 break;
57:             case (11):
58:                 monthName = "November";
59:                 break;
60:             case (12):
61:                 monthName = "December";
62:         }
63:         time = monthName + " " + day + ", " + year + " "
64:             + hour + ":" + minute;
65:         return time;
66:     }
67: }


The getTime() method in ClockPanel contains the same technique for retrieving the current date and time as the ClockTalk application from Hour 7. This method has the keyword final when it is declared in line 15:

final String getTime() {
    // ...
}

Using final prevents the method from being overridden in a subclass. This is required for ClockPanel to be a GUI component.

The panel is created in the constructor in Lines 6–13. The following things are taking place:

• Line 8—The date and time are retrieved by calling getTime() and storing the string it returns in the currentTime variable.

• Line 9—A new label named time is created with the text “Time: “.

• Line 10—currentTime is used as the text of new label component called current.

• Line 11—The time label is added to the clock panel by calling the panel’s add() method with the label as an argument.

• Line 12—The current label is added to the panel in the same manner.

To try out this panel, create the ClockFrame application, which is defined in Listing 13.4.

Listing 13.4. The Full Text of ClockFrame.java


 1: import java.awt.*;
 2: import javax.swing.*;
 3:
 4: public class ClockFrame extends JFrame {
 5:     public ClockFrame() {
 6:         super("Clock");
 7:         setLookAndFeel();
 8:         setSize(225, 125);
 9:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10:         FlowLayout flo = new FlowLayout();
11:         setLayout(flo);
12:         ClockPanel time = new ClockPanel();
13:         add(time);
14:         setVisible(true);
15:     }
16:
17:     private void setLookAndFeel() {
18:         try {
19:             UIManager.setLookAndFeel(
20:                 "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
21:             );
22:         } catch (Exception exc) {
23:             // ignore error
24:         }
25:     }
26:
27:     public static void main(String[] arguments) {
28:         ClockFrame clock = new ClockFrame();
29:     }
30: }


When you run the application, it should resemble Figure 13.7.

Figure 13.7. Displaying a clock panel component.

Image

Summary

Users have come to expect a point-and-click, visual environment for the programs they run. This expectation makes creating software more of a challenge, but Java puts these capabilities into your hands with Swing, which provides all the classes you need to provide a working, useful GUI—regardless of what kind of setup you’re using to run Java programs.

During the next hour, you learn more about the design of a GUI as you work with layout managers, classes that are used to specify how components are arranged within a container.

Q&A

Q. How are components arranged if I don’t assign a layout manager to a container?

A. In a simple container such as a panel, components are arranged using FlowLayout by default. Each component is added in the same manner that words are displayed on a page in English, from left to right, then down to the next line when there’s no more room. Frames, windows, and applets use the GridLayout default layout style you learn about during the next hour.

Q. Why do so many of the graphical user interface classes have names preceded by a J, such as JFrame and JLabel?

A. These classes are a part of the Swing framework, which was the second attempt at graphical user interface classes in the Java class library. The Abstract Windowing Toolkit (AWT) was first, and it had simpler class names like Frame and Label.

The AWT classes belong to the java.awt package and related packages, while Swing belong to javax.swing and the like, so they could have the same class names. The use of the J names keeps the classes from being mistaken for each other.

Swing classes also are called Java Foundation Classes (JFC).

Q. Where can I buy an uncut sheet of $1 bills?

A. The U.S. Bureau of Engraving and Printing sells sheets of real $1, $10, $20 and $50 bills at the website www.moneyfactorystore.gov.

A sheet of 32 $1 bills sells for $55, 16 $10 bills for $269, 16 $20 bills for $409, and 16 $50 bills for $900.

The bureau also sells a five-pound bag containing $10,000 of shredded bills for $45.

Workshop

If your brain hasn’t been turned into a GUI mush with this hour’s toil, test your skills by answering the following questions.

Quiz

1. Which user component is used as a container to hold other components?

A. TupperWare

B. JPanel

C. Choice

2. Which of the following must be done first within a container?

A. Establish a layout manager.

B. Add components.

C. Doesn’t matter.

3. What method determines how components are arranged within a container?

A. setLayout()

B. setLayoutManager()

C. setVisible()

Answers

1. B. JPanel. You can add components to the panel and then add the panel to another container such as a frame.

2. A. You must specify the layout manager before the components so you can add them in the correct way.

3. A. The setLayout() method takes one argument: the layout manager object that has the job of deciding where components should be displayed.

Activities

To interface further with the subject of GUI design, undertake the following activities:

• Modify the SalutonFrame application so that it displays “Saluton Mondo!” in the frame’s main area instead of the title bar.

• Create a frame that contains another frame and make both of them visible at the same time.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.157.34