Java Drawing Strings Colors Fonts

Java Drawing Strings Colors Fonts


Java Drawing Strings Colors Fonts

Summary: By the end of this tutorial "Java Drawing Strings Colors Fonts", you will come to know to draw strings in different colors and fonts in graphics.

In the "Drawing Strings" program, the strings are drawn in default black color and with font Dialog. Now, let us redraw the strings with beautiful colors and fonts to make them more attractive. Here, we use two classes java.awt.Color and java.awt.Font.

Program on Java Drawing Strings Colors Fonts


Java Drawing Strings Colors Fonts
Output screen of AttractiveStrings.java of Java Drawing Strings Colors Fonts

In the global position, reference variables are created of three strings (s1, s2 and s3), three colors (clr1, clr2 and clr3) and three fonts (f1, f2 and f3) and are converted into objects in the constructor.

g.drawString(s1, 50, 60);

The string s1 is drawn in default black color and default font Dialog, plain, 12.

g.setColor(clr1);
g.setFont(f1);
g.drawString(s2, 50, 90);

setColor() and setFont() are the methods of Graphics class with which drawing's color and font can be changed. The setColor() takes a Color object as parameter and setFont() takes a Font object as parameter. Now whatever graphics are drawn, like string s2, are painted in color clr1 and font f1 until they are changed.

g.setColor(new Color(225, 100, 80));
g.setFont(new Font("SansSerif", Font.PLAIN, 22));

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code.

In the above statements, anonymous objects of Color and Font are created and passed to setColor() and setFont() methods. Usage of anonymous objects saves memory on the client machine. In AWT, we use very frequently anonymous objects. Observe, in the constructor we created an anonymous object of AttractiveStrings class and called the constructor.

Note: Using the color range outside 0 to 255 throws IllegalArgumentException.

Leave a Reply

Your email address will not be published. Required fields are marked *