Java Reference
In-Depth Information
You can use the setBackground(Color c) and setForeground(Color c) methods
defined in the java.awt.Component class to set a component's background and foreground
colors. Here is an example of setting the background and foreground of a button:
JButton jbtOK = new JButton( "OK" );
jbtOK.setBackground(color);
jbtOK.setForeground( new Color( 100 , 1 , 1 ));
Alternatively, you can use one of the 13 standard colors ( BLACK , BLUE , CYAN , DARK_GRAY ,
GRAY , GREEN , LIGHT_GRAY , MAGENTA , ORANGE , PINK , RED , WHITE , and YELLOW ) defined as
constants in java.awt.Color . The following code, for instance, sets the foreground color of
a button to red:
jbtOK.setForeground(Color.RED);
12.16 How do you create a color? What is wrong about creating a Color using new
Color(400, 200, 300) ? Which of two colors is darker, new Color(10, 0, 0)
or new Color(200, 0, 0) ?
12.17 How do you create a Color object with a random color?
12.18 How do you set a button object jbtOK with blue background?
Check
Point
12.8 The Font Class
Each GUI component has the font property. Fonts are objects created from the Font class.
Key
Point
You can create a font using the java.awt.Font class and set fonts for the components using
the setFont method in the Component class.
The constructor for Font is:
public Font(String name, int style, int size);
You can choose a font name from SansSerif , Serif , Monospaced , Dialog , and
DialogInput , choose a style from Font.PLAIN ( 0 ), Font.BOLD ( 1 ), Font.ITALIC ( 2 ),
and Font.BOLD Font.ITALIC ( 3 ), and specify a font size of any positive integer. For
example, the following statements create two fonts and set one font to a button.
+
Font font1 = new Font( "SansSerif" , Font.BOLD, 16 );
Font font2 = new Font( "Serif" , Font.BOLD + Font.ITALIC, 12 );
JButton jbtOK = new JButton( "OK" );
jbtOK.setFont(font1);
Tip
If your system supports other fonts, such as “Times New Roman,” you can use the font to
create a Font object. To find the fonts available on your system, you need to obtain
an instance of java.awt.GraphicsEnvironment using its static method
getLocalGraphicsEnvironment() . GraphicsEnvironment is an abstract class
that describes the graphics environment on a particular system. You can use its
getAllFonts() method to obtain all the available fonts on the system and its
getAvailableFontFamilyNames() method to obtain the names of all the available
fonts. For example, the following statements print all the available font names in the system:
find available fonts
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for ( int i = 0 ; i < fontnames.length; i++)
System.out.println(fontnames[i]);
 
 
Search WWH ::




Custom Search