// MyPanel1.java // -- extends MyPanel.java to show the use of text fonts /* * Font families have several attributes: * (1) Font name. E.g. Helvetica, Times Roman * (2) Font style. E.g., PLAIN, BOLD, ITALIC * (3) Font size. E.g., 12 Point * To construct a Font object, do * Font helvb14 = new Font("Helvetica", Font.BOLD, 14); * To use the font, call the setFont method in the graphics object g: * g.setFont(helvb14); * You can also specify font styles such as * Font.BOLD + Font.ITALIC * Use "getAvailableFontFamilyNames" of GraphicsEnvironment class to * determine the fonts you can use. * Instead of Font names, AWT defines 5 "logical font names": * SansSerif, Serif, Monospaced, Dialog, DialogInput * which are always available. * * These concepts are illustrated below in our elaborated * "paintComponent" method. The goal is ostensibly to print * "Hello" in bold and "World!" in bold-italic fonts. * To do this, we need to get the "FontMetrics" object * which has methods to measure the length of a string, say. **/ import java.awt.*; import java.awt.event.*; import javax.swing.*; // text panel class textPanel extends JPanel { // override the paintComponent method // THE MAIN DEMO OF THIS EXAMPLE: public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("SansSerif", Font.BOLD, 14); Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14); FontMetrics fm = g.getFontMetrics(f); FontMetrics fim = g.getFontMetrics(fi); int cx = 75; int cy = 100; g.setFont(f); g.drawString("Hello, ", cx, cy); cx += fm.stringWidth("Hello, "); g.setFont(fi); g.drawString("World!", cx, cy); } //paintComponent } //class textPanel class MyFrame extends JFrame { public MyFrame(String s) { // Frame Parameters setTitle(s); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) // Window Listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } //windowClosing }); //addWindowLister // Add Panels Container contentPane = getContentPane(); contentPane.add(new textPanel()); } //constructor MyFrame } //class MyFrame public class MyPanel1 { public static void main(String[] args) { JFrame f = new MyFrame("My Hello World Frame"); f.show(); } //main } //class MyPanel1 /* NOTES: The java.awt.FontMetrics.* class also has methods to get other properties of the font: its ascent, descent, leading, height, etc. */