Font
ClassColors and fonts are represented in Java by the Color
and Font
classes in the java.awt
package. With these classes, you can present text in different fonts and sizes and change the color of text and graphics. Fonts are created with the Font(
String, int
,
int)
constructor, which takes three arguments:
• The typeface of the font as either a generic name (“Dialog,” “DialogInput,” “Monospaced,” “SanSerif,” or “Serif”) or an actual font name (“Arial Black,” “Helvetica,” or “Courier New”)
• The style as one of three class variables: Font.BOLD
, Font.ITALIC
, or Font.PLAIN
• The size of the font in points
The following statement creates a 12-point italic Serif Font
object:
Font current = new Font("Serif", Font.ITALIC, 12);
If you use a specific fonts rather than one of the generic ones, it must be installed on the computer of users running your program. You can combine the font styles by adding them together, as in the following example:
Font headline = new Font("Courier New", Font.BOLD + Font.ITALIC, 72);
When you have a font, you call the Graphics2D
component’s setFont(
Font)
method to designate it as the current font. All subsequent drawing operations use that font until another one is set. Statements in the following example create a “Comic Sans” font object and designate it as the current font before drawing text:
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D) comp;
Font font = new Font("Comic Sans", Font.BOLD, 15);
comp2D.setFont(font);
comp2D.drawString("Potrzebie!", 5, 50);
}
Java supports antialiasing to draw fonts and graphics more smoothly and less blocky in appearance. To enable this functionality, you must set a rendering hint in Swing. A Graphics2D
object has a setRenderingHint(
int,
int)
method that takes two arguments:
• The key of the rendering hint
• The value to associate with that key
These values are class variables in the RenderingHints
class of java.awt
. To activate antialiasing, call setRenderingHint()
with two arguments:
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
The comp2D
object in this example is the Graphics2D
object that represents a container’s drawing environment.
3.14.130.45