The above output is produced by the following Java code:
import javax.swing.*; import java.awt.*; public class Metrics1 { public static void main(String[] args) { SwingApp app = new SwingApp(200, 400); // set app window size app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class SwingApp extends JFrame { private final DrawPanel panel; // class variable private final Font font1, font2, font3; public SwingApp(int width, int height) // class constructor { super(); // call to super class constructor font1 = new Font("Courier New", Font.PLAIN, 16); font2 = new Font("Times New Roman", Font.ITALIC, 18); font3 = new Font("Harrington", Font.BOLD, 24); Container pane = super.getContentPane(); // create layout, set colors panel = new DrawPanel(); // add GUI components panel.setBackground(Color.yellow); panel.setLayout(new GridLayout(17,1)); addLabel("Courier New", font1); showMetrics(panel, font1); addLabel("", font1); addLabel("Times New Roman", font2); showMetrics(panel, font2); addLabel("", font2); addLabel("Harrington", font3); showMetrics(panel, font3); pane.add(panel); Toolkit toolkit = Toolkit.getDefaultToolkit(); // optionally position JFrame Dimension screenSize = toolkit.getScreenSize(); // in the middle of the screen super.setLocation((screenSize.width - width)/2, (screenSize.height - height)/2); super.setTitle("Swing app"); // set desired window title super.setSize(width, height); // set desired window size super.setVisible(true); } public final void showMetrics(JPanel p, Font f) { int leading = p.getFontMetrics(f).getLeading(); int ascent = p.getFontMetrics(f).getAscent(); int descent = p.getFontMetrics(f).getDescent(); int height = p.getFontMetrics(f).getHeight(); System.out.printf("%d %d %d %d %s\n", leading, ascent, descent, height, f); addLabel("leading is " + leading, f); addLabel("ascent is " + ascent, f); addLabel("descent is " + descent, f); addLabel("height is " + height, f); } public final void addLabel(String s, Font f) { JLabel jl = new JLabel(s, SwingConstants.LEFT); jl.setFont(f); panel.add(jl); } } class DrawPanel extends JPanel // main window panel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); // must be the 1st line // add here more code for drawing on panel } } |