Blakes 21 Days Chapter 09 Document
Day 9, Working with Swing
- Top
- 256 Computer users today expect the software they use to feature a graphical user interface (GUI) with a variety of widgets such as text boxes, sliders, and scrollbars.
- The Java Class Library includes a set of packages called Swing that enables Java programs to offer a sophisticated GUI and collect user input with the mouse, keyboard, and other input devices.
- 256 Today, you will use Swing to create applications that feature these GUI components:
- Frames - Windows that can include a title bar, menu bar, and Maximize, Minimize, and Close buttons
- Containers - interface elements that can hold other components
- Buttons - Clickable regions with text or graphics indicating their purpose
- Labels - Text or graphics that provide information
- Text fields and text areas - Windows that accept keyboard input and allow text to be edited
- Drop-down lists - Groups of related items that can be selected from drop-down menus or scrolling windows
- Check boxes and radio buttons - Small squares or circles that can be selected or deselected
- Image icons - Graphics that can be added to buttons, labels, and other components
- Scrolling panes - Panels that hold components too big for a user interface that are accessed in full with a scrollbar
Creating an Application
- Top
- 256 Swing enables you to create a Java program with an interface that adopts the style of the native operating system,
- such as Windows or Linux, or a style that's unique to Java.
- Each of these styles is called a look and feel because it describes both the appearance of the interface and how its components function when they are used.
- 256 Java offers a distinctive new look and feel called Nimbus that's unique to the language.
- 256 Swing components are part of the javax.swing package, a standard part of the Java Class Library.
- To refer to a Swing class using its short name - without referring to the package,
- in other words - you must make it available with an import statement or use a catchall statement such as the following:
- import javax.swing.*;
- 256 Two other packages that are used to support GUI programming
- are java.awt, the Abstract Windowing Toolkit (AWT),
- and java.awt.event, event-handling classes that handle user input.
- 256 When you use a Swing component, you work with objects of that component's class.
- You create the component by calling its constructor and then calling methods of the component as needed for proper setup.
- 256 All Swing components are subclasses of the abstract class JCompent.
- It includes methods to
- set a component's size,
- change the background color,
- define the font used for any displayed text,
- and set up ToolTips.
- These are explanatory text that appears when you hover the mouse over the component for a few seconds
- Top
- 256 CAUTION: Swing classes inherit from many of the same superclasses as the Abstract Windowing Toolkit,
- so it is possible to use Swing and AWT components together in the same interface.
- However, the two types of components will not be rendered correctly in a container, so it's best to always use Swing components - there's one for every AWT component.
- Top
- 256 Before components can be displayed in a user interface, they must be added to a container, a component that can hold other components.
- Swing containers are subclasses of java.awt.Container.
- This class includes methods to add and remove components from a container,
- arrange components using an object called a layout manager,
- and set up borders around the edges of a container.
- Containers often can be placed in other containers.
Creating an Interface
- Top
- 257 The first step in creating a Swing application is to create a class that represents the main GUI.
- An object of this class serves as a container that holds all other components to be displayed.
- 257 In many projects, the main interface object is a frame (the JFrame class).
- Frames are the window shown whenever you open an application on your computer, regardless of the language it was programmed in.
- Frames have a
- Title Bar,
- Maximize, Minimize, and Close buttons,
- and other features.
- 257 In a graphical environment such as Windows or Mac OS, users expect to be able to move, resize, and close the windows of programs they run.
- One way to create a graphical Java application is to make the interface a subclass of JFrame, as in the following class declaration:
public class FeedReader extends JFrame {
// body of class
}
- The constructor of the class should handle the following tasks:
- Call a superclass constructor to give the frame a title and handle other setup procedures.
- Set the size of the frame's window, either by specifying the width and height in pixels or by letting Swing choose the right size.
- Decide what to do if a user closes the window.
- Display the frame.
- Top
- 257 The JFrame class has the simple constructors JFrame() and JFrame(String).
- One sets the frame's title bar to the specified text, and the other leaves the title bar empty.
- You also can set the title by calling the frame's setTitle(String) method.
- 257 The size of a frame can be established by calling the setSize(int, int) method with the width and height as arguments.
- A frame's size is indicated in pixels, so calling setSize(650, 550) creates a frame 650 pixels wide and 550 pixels tall,
- taking up most of a screen that has 800x600 resolution.
- Top
- 258 NOTE: You also can call the method setSize(Dimension) to set up a frame's size.
- Dimension is a class in the java.awt package that represents the width and height of a user interface component.
- Calling the Dimension(int, int)constructor creates a Dimension object representing the width and height specified as arguments.
- Top
- 258 Another way to set a frame's size is to fill the frame with the components it will contain and then call the frame's pack() method.
- This resizes the frame based on the size of the components inside it.
- If the frame is bigger than it needs to be, pack() shrinks it to the minimum size required to display the components.
- If the frame is too small (or the size has not been set), pack() expands it to the required size.
- 258 Frames are invisible when they are created.
- You make them visible by calling the frame's setVisible(boolean) method with the literal true as an argument.
- 258 If you want a frame to be displayed when it is created, call one of these methods in the constructor.
- You also can leave the frame invisible, requiring any class that uses the frame to make it visible by calling setVisible(true).
- Calling setVisible(false) makes the frame invisible.
- Top
- 258 When a frame is displayed, the default behavior is for it to be positioned in the upper-left corner of the computer's desktop.
- You can specify a different location by calling the setBounds(int, int, int, int) method.
- The first two arguments to this method are the (x,y) position of the frame's upper-left corner on the desktop.
- The last two arguments set the frame's width and height.
- 258 Another way to set the bounds is with a Rectangle object from the java.awt package.
- Create the rectangle with the Rectangle(int, int, int, int) constructor.
- The first two arguments are the (x,y) position of the upper-left corner.
- The next two are the width and height.
- Call setBounds(Rectangle) to draw the frame at that spot.
- Top
- 258 The following class represents a 300 X 100 frame with "Edit Payroll" in the title bar.
public class Payroll extends javax.swing.JFrame {
public Payroll() {
super("Edit Payroll");
setSize(300, 100);
setVisible(true);
}
}
- Top
- 259 Every frame has Maximize, Minimize, and Close buttons on the title bar that the user can control,
- the same controls present in the interface of other software running on your computer.
- 259 The normal behavior when a frame is closed is for the application to keep running.
- When a frame serves as a program's main GUI, this leaves a user with no way to stop the program.
- 259 To change this, you must call a frame's setDefaultCloseOperation() method with one of four static variables as an argument:
- EXIT_ON_CLOSE - Exits the application when the frame is closed
- DISPOSE_ON_CLOSE - Closes the frame, removes the frame object from Java Virtual Machine (JVM) memory, and keeps running the application
- DO_NOTHING_ON_CLOSE - Keeps the frame open and continues running
- HIDE_ON_CLOSE - Closes the frame and continues running
- Top
- 259 These variables are in the JFrame class because it implements the WindowConstants interface.
- To prevent a user from closing a frame, add the following statement to the frame's constructor method:
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- If you are creating a frame to serve as an application's main user interface, the expected behavior is probably EXIT_ON_CLOSE,
- which shuts down the application along with the frame.
- Top
- 259 As mentioned earlier, you can customize the overall appearance of a user interface in Java by designing a look and feel.
- The UIManager class in the javax.swing package manages this aspect of Swing.
- To set the look and feel, call the class method setLookAndFeel(String) with the name of the look and feel's class as the argument.
- Here's how to choose the Nimbus look and feel:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
- 259 This method call should be contained within a try-catch block because it might generate five different exceptions.
- Catching the Exception class and ignoring it
- causes the default look and feel to be used in the unlikely circumstance that Nimbus can't be chosen properly.
- Top
- 260 CAUTION: Using EXIT_ON_CLOSE shuts down the entire JVM, so it should be used only in the frame for an application's main window.
- If anything needs to happen after the frame closes, DISPOSE_ON_CLOSE or HIDE_ON_CLOSE should be used instead.
Developing a Framework
- Top
- 260 Today's first project is an application that displays a frame containing no other interface components.
- In NetBeans, create a new Java file with the class name SimpleFrame and the package name com.java21days,
- then enter Listing 9.1 as the source code.
- This simple application displays a frame 300 X 100 pixels in size and can serve as a framework for any application you create that use a GUI
Listing 9.1
- Top
- page 260
package com.java21days;
import javax.swing.*;
public class SimpleFrame extends JFrame {
public SimpleFrame() {
super("Frame Title");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] arguments) {
setLookAndFeel();
SimpleFrame sf = new SimpleFrame();
}
}
Listing 9.1 - The full Text
- Top
- 261 When you compile and run the application, you should see the frame displayed as in Figure 9.1
Figure 9.1 Displaying a frame.
- Top
- 261 The SimpleFrame application isn't much to look at.
- The GUI contains no components, aside from the standard Minimize, Maxinize, and Close (X) buttons on the title bar, as shown in Figure 9.1.
- You add components later today.
- 261 In the application, a SimpleFrame object is created in the main() method in lines 24 - 27.
- If you had not displayed the frame when it was constructed, you could call sf.setVisible(true) in the main() method to display the frame.
- 261 Nimbus is set as the frame's look and feel in lines 16 - 18.
- 261 The work involved in creating the frame's user interface takes place in the SimpleFrame() constructor in lines 6 - 12.
- Components can be created and added to the frame within this constructor.
Creating a Component
- Top
- 261 Creating a GUI is a great way to get experience working with objects in Java, because each interface component is represented by its own class.
- 261 To use an interface component in Java, you create an object of that component's class.
- You already have worked with the container class JFrame.
- 261 One of the simplest components to employ is JButton, the class that represents clickable buttons.
- In most programs, buttons trigger an action.
- You can click Install to begin installing software,
- click a smiley button to begin a new game of Angry Birds, click the Minimize button to prevent your boss from seeing Angry Birds running, and so on.
- 261 A Swing button can feature a text label, a graphical icon, or a combination of both.
- 261 Constructors you can use for buttons include the following:
- JButton(String) - A button labeled with specific text
- JButton(Icon) - A button that displays the specified icon
- JButton(String, Icon) - A button with the specified text and graphical icon
- Top
- 262 The following statements create three buttons with text labels:
- JButton play = new JButton("Play");
- JButton stop = new JButton("Stop");
- JButton rewind = new JButton("Rewind");
- Graphical buttons are covered later today.
Adding Components to a Container
- Top
- 262 Before you can display a user interface component such as a button in a Java program, you must add it to a container and display that container
- 262 To add a component to a container, call the container's add(Component) method with the component as the argument
- (all user interface components in Swing inherit from java.awt.Component).
- 262 The simplest Swing container is a panel (the JPanel class).
- The following example creates a button and adds it to a panel:
JButton quit = new JButton("Quit");
JPanel panel = new JPanel();
panel.add(quit);
- 262 Use the same technique to add components to frames and windows.
Second Program
- Top
- 262 The ButtonFrame class, shown in Listing 9.2, expands on the application framework created earlier today.
- A panel is created, three buttons are added to the panel, and then it is added to a frame.
- Top
- Enter the source code of Listing 9.2 into a new Java file called ButtonFrame in NetBeans, making sure to put it in the com.java21days package.
Listing 9.2 - The Full Text of ButtonFrame.java
- Top
- page 262 - 263
package com.java21days;
import javax.swing.*;
public class ButtonFrame extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super("Button Title");
setSize(340, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
setLookAndFeel();
ButtonFrame bf = new ButtonFrame();
}
}
Listing 9.2 - The Full Text of ButtonFrame.java
- Top
- 263 When you run the application, a small frame opens that contains the three buttons, as shown in Figure 9.2
Figure 9.2 The Button Frame application.
- Top
- 263 The ButtonFrame class has three instance variables: the load, save, and unsubscribe JButton objects.
- 263 In lines 14 - 17 of Listing 9.2, a new JPanel object is created, and the three buttons are added to the panel by calls to its add(Component) method.
- When the panel contains all the buttons, the frame's own add(Component) method is called in line 18 with the panel as an argument, adding it to the frame.
- Top
- 264 NOTE: If you click the buttons, nothing happens.
- Doing something in response to a button click is covered in Day 12, "Responding to User Input."
Working with Components
- Top
- 264 Swing offers more than two dozen user interface components in addition to the buttons and containers you have used so far.
- You will work with many of these components for the rest of the day and on Day 10, "Building a Swing Interface."
- 264 All Swing components share a common superclass, javax.swing.JComponent, from which they inherit several methods you will find useful in your own programs.
- 264 The setEnabled(boolean) method determines whether a component can receive user input (an argument of true) or is inactive and cannot receive input (false).
- Components are enabled by default.
- Many components change in appearance to indicate when they are not presently usable.
- For instance, a disabled JButton has light gray borders and gray text.
- If you want to check whether a component is enabled, you can call the isEnabled() method, which returns a boolean value.
- Top
- 264 The setVisible(boolean) method works for all components the way it does for containers.
- Use true to display a component and false to hide it.
- 264 The setSize(int, int) method resizes the component to the width and height specified as arguments,
- and setSize(Dimension) uses uses a Dimension object to accomplish the same thing.
- For most components, you don't need to set a size, the default is usually acceptable.
- To find out a component's size, call its getSize() method, which returns a Dimension object with the dimensions in height and width instance variables.
- 264 As you will see, similar Swing components also have other methods in common,
- such as setText() and getText() for text components and setValue() and getValue() for components that store a numeric value.
- Top
- 264 CAUTION: When you begin working with Swing components, a common source of mistakes is to set up aspects of a componet after it has been added to a container.
- Be sure to set up a component fully before placing it in a panel or any other container.
Image Icons
- Top
- 265 Swing supports the use of graphical ImageIcon objects on buttons and other components in which a label can be provided.
- An icon is a small graphic that can be placed on a button, label, or other user interface element to identify it.
- Examples include a garbage can or recycling bin icon for deleting files, and folder icons for opening and storing files.
- 265 You can create an ImageIcon object by specifying the filename of a graphic as the only argument to the constructor.
- The following example loads an icon from the graphics file subscribe.gif and creates a JButton with the icon as its label:
ImageIcon subscribe = new ImageIcon("subscribe.gif");
JButton button = new JButton(subscribe);
JPanel pane = new JPanel();
panel.add(button);
add(pane);
setVisible(true);
Third Program
- Top
- 265 Listing 9.3 is a Java application that creates four image icons with text labels, adds them to a panel, and then adds the panel to a frame.
- 265 Create a new empty Java file in NetBeans for a class named IconFrame in the package com.java21days, and enter this listing with the source file editor.
Listing 9.3 - The Full Text of IconFrame.java
- Top
- page 265 - 266
package com.java21days;
import javax.swing.*;
public class IconFrame extends JFrame {
JButton load, save, subscribe, unsubscribe;
public IconFrame() {
super("Icon Title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
// create icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subscribeIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubscibeIcon = new ImageIcon("unsubscibe.gif");
// create buttons
load = new JButton("Load", loadIcon);
save = new JButton("Save", saveIcon);
subscribe = new JButton("Subscribe", subscribeIcon);
unsubscribe = new JButton("Unsubscribe", unsubscribeIcon);
// add buttons to panel
pane.add(load);
pane.add(save);
pane.add(subscribe);
pane.add(unsubscribe);
// add the panel to a frame
add(panel);
pack();
setVisible(true);
}
public static void main(String[] arguments) {
setLookAndFeel();
IconFrame ike = new IconFrame();
}
}
- Top
- 266 Figure 9.3 shows the result
Figure 9.3 goes here
- Top
- 266 The icons' graphic referred to in lines 13 - 16 can be found on the book's official website at www.java21days.com on the Day 9 page.
- 266 In NetBeans, the graphics must be part of the project before this application runs correctly.
- The graphics need to be stored in the main folder of the Java21 project you've been using throughout this book to hold the classes you create.
- Follow these steps:
- Save the graphics files to a temporary folder on your computer.
- Click the Files tab to bring that pane to the front. The Files tab opens, as shown in Figure 9.4, listing the files in the project.
- Drag and drop the four graphics files into the Java21 folder in this pane.
Figure 9.4 goes here (Dragging files into the NetBeans Files pane.)
- Top
- 267 the IconFrame application does not set the size of the frame in pixels.
- Instead, the pack() method is called in line 29 to expand the frame to the minimum size required to present the four buttons next to each other.
- 267 If the frame were set to be tall rather than wide, for instance, by calling setSize(100, 400) in the constructor, the buttons would be stacked vertically.
- Top
- 267 NOTE: Some of the project's graphics are from Oracle's Java Look and Feel Graphics Repository, a collection of icons suitable for use in your own programs.
- If you're looking for icons to experiment with in Swing applications, you can find some at the following address:
Labels
- Top
- 267 A label is a user component that holds text, an icon, or both.
- Labels, which are created from the JLabel class, identify the purpose of other components on an interface.
- A user cannot edit them directly.
- 267 To create a label, you can use these simple constructors:
- JLabel(String) - A label with the specified text
- JLabel(String, int) - A label with the specified text and alignment
- JLabel(String, Icon, int) - A label with the specified text, icon, and alignment
- Top
- 267 A label's alignment determines how its text or icon is aligned in relation to the area taken up by the window.
- Three static class variables of the SwingConstants interface are used to specify alignment: LEFT, CENTER, and RIGHT.
- 267 You can set a label's contents with the setText(String) or setIcon(Icon) methods.
- You also can retrieve these things with the getText() and getIcon() methods.
- 267 The following statements create three labels with left, center, and right alignment, respectively:
- JLabel feedsLabel1 = new JLabel ("Feeds: ", SwingConstants.LEFT);
- JLabel urlLabel = new JLabel ("URL: ", SwingConstants.CENTER);
- JLabel dateLabel = new JLabel ("Date: ", SwingConstants.RIGHT);
Text Fields
- Top
- 268 A text field is a location on an interface where a user can enter and modify text using the keyboard.
- Text fields are represented by the JTextField class, and each can handle one line of input.
- The next section describes a text area component that can handle multiple lines.
- 268 Constructors for text fields include the following:
- JTextField() - An empty text field
- JTextField(int) - A text field with the specified width
- JTextField(String, int) - A text field with the specified text and width
- 268 A text field's width attribute has relevance only if the interface is organized in a manner that does not resize components.
- You get more experience with this when you work with layout managers on Day 11, "Arranging Components on a User Interface."
- Top
- 268 The following statements create an empty text field that has enough space for roughly 60 characters and a text field of the same size with the starting text "Enter feed URL here":
- JTextField rssUrl = new JTextField(60);
JTextField rssUrl2 = new JTextField("Enter feed URL here", 60);
- 268 Text fields and text areas both inherit from the superclass JTextComponent and share many common methods.
- 268 The setEditable(boolean) method determines whether a text component can be edited (true) or not (false).
- An isEditable() method returns a corresponding boolean value.
- Top
- 268 The setText(String) method changes the text to the specified string, and the getText() method returns the component's current text as a string.
- Another method retrieves only the text that a user has highlighted in the getSeletedText() component.
- 268 Password fields are text fields that hide the characters a user types into the field.
- They are represented by the JPasswordField class, a subclass of JTextField.
- The JPasswordField constructors take the same arguments as those of the parent class.
- 268 After you have created a password field, call its setEchoChar(char) method to obscure input by replacing each input character with the specified character.
- The following statements create a password field and set its echo character to #:
- JPasswordField codePhrase = new JPasswordField(20);
codePhrase.setEchoChar('#');
Text Areas
- Top
- 269 Text areas, editable text fields that can handle more than one line of input, are implemented by the JTextArea class, which includes these constructors:
- JTextArea(int, int) - A text area with the specified number of rows and columns
- JTextArea(String, int, int) - A text area with the specified text, rows, and columns
- 269 You can use the getText(), getSelectedText(), and setText(String) methods with text areas as you would text fields.
- Also, an append(String) method adds the specified text at the end of the current text,
- and an insert(String, int) method inserts the specified text at the indicated position.
- 269 The setLineWrap(boolean) method determines whether text will wrap to the next line when it reaches the right edge of the component.
- Call setLineWrap(true) to cause line wrapping to occur.
- Top
- 269 The setWrapStyleWord(boolean) method determines what wraps to the next line,
- either the current word (true) or the current character (false).
Fourth Program
- Top
- 269 The next project you create, the Authenticator application shown in Listing 9.4, uses several Swing components to collect user input: a text feld, a password field, and a text area.
- Labels also are used to indicate the purpose of each text component.
- 269 In NetBeans, create an empty Java file called Authenticator in the package com.java21days.
Listing 9.4 - The Full Text of Authenticator.java
- Top
- page 269 - 270
package com.java21days;
import javax.swing.*;
public class Authenticator extends javax.swing.JFrame {
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JTextArea comments = new JTextArea(4, 15);
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
public Authenticator() {
super("Account Information");
setSize(300, 220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel usernameLabel = new JLabel("Username: ");
JLabel passwordLabel = new JLabel("Password: ");
JLabel commentsLabel = new JLabel("Comments: ");
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
pane.add(usernameLabel);
pane.add(username);
pane.add(passwordLabel);
pane.add(password);
pane.add(commentsLabel);
pane.add(comments);
pane.add(ok);
pane.add(cancel);
add(panel);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
Authenticator.setLookAndFeel();
Authenticator auth = new Authenticator();
}
}
- Top
- 270 This application sets up components and adds them to a panel in lines 17 - 30.
- Figure 9.5 shows the application in use.
- The password is obscured with asterisk characters (*),
- which is the default when no other echo character is designated by calling the field's setEchoChar(char) method.
Figure 9.5 goes here
- Top
- 271 The text area in this application behaves in a manner that you might not expect.
- When you reach the bottom of the field and continue entering text,
- the component grows to make more room for input (and even scrolls below the bottom edge of the frame).
- The next section describes how to add scrollbars to prevent the area from changing in size.
Scrolling Panes
- Top
- 271 Text areas in Swing do not include horizontal or vertical scrollbars, and there's no way to add them using this component alone.
- Swing supports scrollbars through a new container that can be used to hold any component that can be scrolled: JScrollPane.
- A scrolling pane is associated with a component in the pane's constructor.
- You can use these following constructors:
- JScrollPane(Component) - A scrolling pane that contains the specified component
- JScrollPane(Component, int, int) - A scrolling pane with the specified component, vertical scrollbar configuration, and horizontal scrollbar configuration.
- 271 Scrollbars are configured using one of six static class variables of the ScrollPaneConstants interface.
- There are three for vertical scrollbars:
- VERTICAL_SCROLLBAR_ALWAYS
- VERTICAL_SCROLLBAR_AS_NEEDED
- VERTICAL_SCROLLBAR_NEVER
- There are also three variables for horizontal scrollbars with similar names.
- After you create a scrolling pane containing a component, you should add the pane to containers in place of that component.
- The following example creates a text area with a vertical scrollbar and no horizontal scrollbar and then adds it to a container.
JPanel pane = new JPanel();
JTextArea comments = new JTextArea(4, 15);
JScrollPane scroll = new JScrollPane(comments,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.add(scroll);
add(pane);
- Top
- 272 NOTE: This book's website contains Authenticator2, a full application that makes use of this code.
Check Boxes and Radio Buttons
- Top
- 272 The next two components, check boxes and radio buttons, hold only two possible values: selected or not selected.
- 272 Check boxes are used to make a simple choice in an interface, such as yes/no or on/off.
- 272 Radio buttons are grouped so that only one button can be selected at any time.
- 272 Check boxes (the JCheckBox class) appear as labeled or unlabeled boxes that contain a check mark when they are selected and nothing otherwise.
- Radio buttons (the JRadioButton class) appear as circles that contain a dot when selected and nothing otherwise.
- 272 Both the JCheckbox and JRadioButton classes have several useful methods inherited from JToggleButton, their common superclass:
- setSelected(boolean) - Selects the component if the argument is true and deselects it otherwise.
- isSelected() - Returns a boolean indicating whether the component is correctly seleted.
- 272 The following constructors can be used for the JCheckBox class:
- JCheckBox(String) - A check box with the specified text label
- JCheckBox(String, boolean) - A check box with the specified text label that is selected if the second argument is true
- JCheckBox(Icon) - A check box with the specified graphical icon
- JCheckBox(Icon, boolean) - A check box with the specified graphical icon that is selected if the second argument is true
- JCheckBox(String, Icon) - A check box with the specified text label and graphical icon
- JCheckBox(String, Icon, boolean) - A check box with the specified text label and graphical icon that is selected if the third argument is true
- Top
- 272 The JRadioButton class has constructors with the same arguments and functionality
- 273 Check boxes and radio buttons by themselves are nonexclusive,
- meaning that if you have five check boxes in a container, all five can be checked or unchecked at the same time.
- To make them exclusive, as radio buttons should be, you must organize related components into groups.
- To organize several radio buttons into a group, allowing only one to be selected at a time, create a ButtonGroup class object, as demonstrated in the following statement:
- ButtonGroup choice = new ButtonGroup();
- The ButtonGroup object keeps track of all radio buttons in its group.
- Call the group's add(Component) method to add the specified component to the group.
- The following example creates a group and two radio buttons that belong to it:
ButtonGroup saveFormat = new ButtonGroup();
JRadioButton s1 = new JRadioButton("JSON", false);
saveFormat.add(s1);
JRadioButton s2 = new JRadioButton("XML", true);
saveFormat.add(s2);
- The saveFormat object groups the s1 and s2 radio buttons.
- The s2 object, which has the label "XML", is selected.
- Only one member of the group can be selected at a time.
- If one component is selected, the ButtonGroup object ensures that all others in the group are deselected.
Fifth Program
- Top
- 273 Create a new empty Java file in NetBeans called FormatFrame in the package com.java21days.
- Enter the source code shown in Listing 9.5 to create an application with four radio buttons in a group.
Listing 9.5 - The Full Text of FormatFrame.java
- Top
- page 273 - 274
package com.java21days;
import javax.swing.*;
public class FormatFrame extends JFrame {
JRadioButton[] teams = new JRadioButton[4];
public FormatFrame() {
super("Choose an Output Format");
setSize(320, 120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
teams[0] = new JRadioButton("Atom");
teams[1] = new JRadioButton("RSS 0.92");
teams[2] = new JRadioButton("RSS 1.0");
teams[3] = new JRadioButton("RSS 2.0", true);
JPanel panel = new JPanel();
JLabel chooseLabel = new JLabel(
"Choose an output format for syndicated news items.");
panel.add(chooseLabel);
pane.add(passwordLabel);
ButtonGroup group = new ButtonGroup();
for (JRadioButton team : teams) {
group.add(team);
panel.add(team);
}
add(panel);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
FormatFrame.setLookAndFeel();
FormatFrame ff = new FormatFrame();
}
}
Explanation
- Top
- 274 Figure 9.6 shows the application running.
- The four JRadioButton objects are stored in an array in lines 12 - 15.
- In the for loop in lines 21 - 24, each element is first added to a button group and then is added to a panel.
- After the loop ends, the panel is added to the frame.
Figure 9.6 goes here
- Top
- 274 Choosing one of the radio buttons causes the existing choice to be deselected.
Combo Boxes
- Top
- 274 The Swing class JComboBox can be used to create combo boxes,
- components that present a drop-down menu from which a single value can be selected.
- The menu is hidden when the component is not being used, thus taking up less space in a GUI.
- 275 After a combo box is created by calling the JComboBox() constructor with no arguments,
- the combo box's addItem(Object) method adds items to the list.
- Another way to create a combo box is to call JComboBox(Object[]) with an array that contains the items.
- If the items are text, a String array would be the argument.
- In a combo box, users can select only one of the items on the drop-down menu.
- If the component's setEditable() method is called with true as an argument, it also supports text entry.
- This feature gives combo boxes their name, a component configured in this manner serves as both a drop-down menu and a text field.
- Top
- 275 The JComboBox class has several methods you can use to control a drop-down list or combo box:
- getItemAt(int) - Returns the text of the list item at the index position specified by the integer argument.
- As with arrays, the first item of a choice list is at index position 0, the second is at position 1, and so on.
- getItemCount() - Returns the number of items in the list.
- getSelectedIndex() - Returns the index position of the currently selected item in the list.
- getSelectedItem() - Returns the text of the currently selected item.
- getSelectedIndex(int) - Selects the item at the indicated index position.
- getSelectedIndex(Object) - Selects the specified object in the list.
Sixth Program
- Top | (Back to Day 12 - 12.3 The Explanation)
- 275 The FormatFrame2 application, shown in Listing 9.6 rewrites the preceding radio button example.
- The program uses a noneditable combo box from which a user can choose on of four options.
Listing 9.6 - The Full Text of FormatFrame2.java
- Top
- page 275 - 276
package com.java21days;
import javax.swing.*;
public class FormatFrame2 extends JFrame {
String[] formats = { "Atom", "RSS 0.92", "RSS 1.0", "RSS 2.0" };
JComboBox formatBox = new JComboBox(formats);
public FormatFrame2() {
super("Choose a Format");
setSize(220, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JLabel formatLabel = new JLabel("Output formats:");
pane.add(formatLabel);
pane.add(formatBox);
add(pane);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
FormatFrame2.setLookAndFeel();
FormatFrame2 ff = new FormatFrame2();
}
}
Explanation
- Top
- 276 A string array is defined in line 6, and then these strings are used in the combo box constructor in line 7 to set its possible values.
- Figure 9.7 shows the application as the combo box is expanded so that a value can be selected.
Figure 9.7 goes here
Lists
- Top
- 276 The last Swing component to be introduced today is similar to combo boxes.
- Lists, which are represented by the JList class, allow you to select one or more values from a list.
- 276 You can create and fill lists with the contents of an array or vector (a data structure similar to array lists).
- The following constructors are available:
- JList() - Creates an empty list
- JList(Object[]) - Creates a list that contains an array of the specified class (such as String)
- JList(Vector<Class>) - Creates a list that contains the specified java.util.Vector object of the specified class
- Top
- 277 An empty list can be filled by calling its setListData() method with either an array or vector as the only argument.
- Unlike combo boxes, lists display more than one of their rows when they are presented in a user interface.
- The default is to display eight items.
- To change this, call setVisibleRowCount(int) with the number of items to display.
- 277 The getSelectedValuesList() method returns a list of objects containing all the items selected in the list.
- This list can be cast to an ArrayList.
- 277 You can use generics with JList to indicate the class of the object array the list contains.
Seventh Program
- Top
- 277 The Subscriptions application in the com.java21days package, shown in Listing 9.7, displays eight items from an array of strings.
Listing 9.7 - The Full Text of Subscriptions.java
- Top
- page 277 - 278
package com.java21days;
import javax.swing.*;
public class Subscriptions extends JFrame {
String[] subs = { "Burningbird", "Freeform Goodness",
"Ideoplex", "Inessential", "Intertwingly", "Now This",
"Rasterweb", "RC3", "Whole Lotta Nothing", "Workbench" };
JList<String> subList = new JList<>(subs);
public Subscriptions() {
super("Subscriptions");
setSize(150, 335);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel subLabel = new JLabel("RSSSubscriptions:");
panel.add(subLabel);
subList.setVisibleRowCount(8);
JScrollPane scroller = new JScrollPane(subList);
panel.add(scroller);
add(panel);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookandFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
Subscriptions.setLookAndFeel();
Subscriptions app = new Subscriptions();
}
}
Explanation
- Top
- 278 The application is shown in Figure 9.8.
- The Subscriptions application has an interface with a label atop a list displaying eight items.
- A Scroll pane is used in lines 19-21 to enable the list to be scrolled to see items 9 and 10.
Figure 9.8 goes here
The Java Class Library
- Top
- 278 The first week of this book was devoted to the building blocks of the Java Language, including statements, expressions, and operators;
- and the components of object-oriented programming (OOP) such as methods, constructors, classes, and interfaces.
- 278 The second week covers how to build things with those blocks by using the Java Class Library.
- A lot of your work as a programmer is done for you, provided you know where to look.
- 278 The Java Class Library contains over 4,200 classes.
- Many of them will be useful in programs that you create.
- Top
- 279 NOTE: There also are Java class libraries produced by other organizations.
- The Apache Project has more than a dozen Java open source projects, including HttpComponents, a set of classes for creating web servers, clients, and crawlers.
- To see these projects, visit http://projects.apache.org.
- Top
- 279 Oracle offers comprehensive documentation for the library on the Web.
- A page from this documentation is shown in Figure 9.9
Figure 9.9 goes here
- Top
- 279 The home page is divided into frames.
- The largest lists all the packages that compose the library with a description of each.
- Package names describe their purpose,
- such as the java.io package of classes for input and output from files, Internet servers, and other data sources,
- and java.time for time and date classes.
- On the home page, the largest frame presents a list of packages with a short description of each one.
- Click the name of a package to load a page listing all of its classes.
- Top
- 280 Each class in the library has its own page of documentation.
- To get a taste of how to use this reference, follow these steps:
- In your web browser, load the page http://docs.oracle.com/javase/8/docs/api
- Scroll down to the java.lang package and click the link. That package's page opens.
- Scroll down to the link for the Math class, aand click it. The page for the class opens.
- Find the random() method link and click it. The page jumps to that section.
- The Math class page describes its purpose and package.
- Use a class page to learn how to create an object of the class and what variables and methods it contains.
- This class has handy methods that extend Java's math capabilities and turn up often in Java applications.
- One is random(), a method that produces a random double value from 0.0 to 1.0
- Here's a statement that uses this method:
- double d100 = Math.random() * 100;
- The random() method produces a randomly generated number ranging from 0.0 up to 1.0, but not including that maximum value.
- This is a floating-point number, so it needs to be stored in a float or double.
- Because this random number is multiplied by 100, the number will be anything from 0 to 100 (not including 100).
- Here's a statement to round the number down to the nearest integer and add 1:
- d100 = Math.floor(roll) + 1;
- This statement uses another method of the Math class, floor(), which rounds a floating-point number down to the closest lower integer.
- A value of 47.52 would be rounded down to 47.
- Adding one makes the value of d100 48.
- Without the Math class, you'd have to create your own class to produce random numbers, which is a highly complex task.
- Top
- 280 Poking around the Java Class Library documentation is a good way to find classes that will save you an enormous amount of time.
- 280 Because you're new to Java, you likely will find some of the documentation difficult to understand
- it's written for experienced programmers.
- But as you read this book and encounter interesting Java classes, use this reference to find out more about them.
- A good place to begin is to look up the methods in a class, each of which performs a job, and see what arguments they take and values they return.
- 281 While you are learning about Swing user interface components and classes during the next five days, check out their pages in the official documentation.
- They have more cool methods than this book has time to cover.
Summary
- Top
- 281 Today you began working with Swing, the package of classes that enables your Java programs to support a GUI.
- Object-oriented programming is beneficial because of its benefits: improved reliability, reusability, and maintenance.
- 281 You used more than a dozen classes today, creating interface components such as buttons, labels, and text fields.
- You put each of these into containers: components that include panels, frames, and windows.
- 281 This kind of programming can be complicated.
- Swing represents the largest package of classes that a new Java programmer must deal with in learning the language.
- 281 However, as you have experienced with components such as text areas and text fields,
- Swing components have many superclasses in common.
- This makes it easier to extend your knowledge into new components and containers,
- along with the other aspects of Swing programming you will explore over the coming days.
Q & A
- Top
- 281 Q Is there a way to change the font of text that appear on a button and other components ?
- 281 A The JComponent class includes a setFont(Font)method that can be used to set the font for text displayed by that component.
- You will work with Font objects, color, and more graphics on Day 13, "Creating Java2D Graphics."
Quiz - Questions
- Which of the following user interface components is not a container ?
- JScrollPane
- JTextArea
- JPanel
- Which componenet can be placed into a Scroll pane ?
- JTextArea
- JTextField
- Any component
- If you use setSize()on an application's main frame, where will it appear on your desktop ?
- At the center of the desktop
- at the same spot the last application appeared
- At the upper-left corner of the desktop
Answers
- Top | Note A is 1, B is 2, and C is 3
- B. A JTextArea requires a container to support scrolling, but it is not a container itself.
- C. Any component can be added to a Scroll pane, but most are unlikely to need scrolling.
- C. Tis is a trick question. Calling setSize() has nothing to do with a window's position on the desktop. You must call setBounds() rather than setSize() to choose where a frame will appear.
Certification Practice
- Top
- 282 The following question is the kind of thing you could expect to be asked on a Java programming certification test.
- Given:
import javax.swing.*;
public class Display extends JFrame {
public Display() {
super("Display");
// answer goes here
JLabel hello = new JLabel("Hello");
JPanel pane = new JPanel();
add(hello);
pack();
setVisible(true);
}
public static void main(String[] arguments) {
Display ds = new Display();
}
}
- What statement needs to replace // answer goes here to make the application function properly ?
- setSize(300, 200);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- Display ds = new Display();
- No statement needed.
Exercise
- Top
- To extend your knowledge of the subjects covered today, try the following exercises:
- Create an application with a frame that includes several DVR commands as individual components:
- play, stop/eject, rewind, fast-forward, and pause.
- Choose a size for the window that enables all the components to be displayed on a single row.
- Create a frame that opens a smaller frame with fields asking for a username and password.