Page 708 - Introduction to Programming with Java: A Problem Solving Approach
P. 708
674
Chapter 16 GUI Programming Basics
}
instructions.setText(briefInstructions);
btn.setText("ShowDetails");
} // end actionPerformed
16.16 Color
So far in this chapter, all of our components have been simple in terms of color—black text on white back- ground or black text on light-gray background. It’s time to add some color. You should get used to adding color to most of your GUI applications. After all, color can enhance a user’s experience with a program by providing visual cues and visual appeal. Remember, color is fun!
Color Methods
Most GUI components are composed of two colors. The foreground color is the color of the text, and the background color is the color of the area behind the text. Let’s jump right into an example that shows you how to set the colors. This code fragment creates a blue button with white text:
JButton btn = new JButton("Click Me");
btn.setBackground(Color.BLUE);
btn.setForeground(Color.WHITE);
And here’s what the blue-white button looks like:
Apago PDF Enhancer
The setBackground and setForeground methods are mutator methods. Here are the API head- ings and descriptions for their associated accessor methods:
public Color getBackground()
Returns the component’s background color.
public Color getForeground()
Returns the component’s foreground color.
Here’s an example that uses the getBackground and getForeground methods with a text box:
JTextField nameBox = new JTextField();
Color originalBackground = nameBox.getBackground();
Color originalForeground = nameBox.getForeground();
Why might you want to save a text box’s original colors? As a visual cue, you might want to change a text box’s colors when the user enters something invalid. And when the user fixes the entry, you’d change back to the original colors. In order to do that, you need to retrieve and save the original colors when the window is first loaded.
You’ve now seen color examples with a button and a text box. Color works the same way for most other components. An exception is the JLabel component. Its background is transparent by default, so if you ap- ply color to it, you won’t see the color. To change a label’s background color, you first have to make it opaque by calling label.setOpaque(true). After that, if you call setBackground(<color>), you’ll see the specified color.