| |
We can get fancier, and mix and match fonts in the display, by using the
Font and FontMetrics classes.
package swingExamples;
import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
class FancyFontDisplayPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Font f = new Font("Serif", Font.PLAIN, 14);
Font fi = new Font("Serif", Font.BOLD | Font.ITALIC, 14);
FontMetrics fm = g.getFontMetrics(f);
FontMetrics fim = g.getFontMetrics(fi);
String s1 = "Hello from a ";
String s2 = "Java Swing ";
String s3 = "application!";
int cx = 20;
int cy = 80;
g.setFont(f);
g.drawString(s1, cx, cy);
cx += fm.stringWidth(s1);
g.setFont(fi);
g.drawString(s2, cx, cy);
cx += fim.stringWidth(s2);
g.setFont(f);
g.drawString(s3, cx, cy);
}
}
class FancyFontDisplayFrame extends JFrame
{
public FancyFontDisplayFrame()
{
setTitle("FancyFontDisplayFrame");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add( new FancyFontDisplayPanel() );
}
}
public class FancyFontDisplay
{
public static void main(String[] args)
{
FancyFontDisplayFrame frame = new FancyFontDisplayFrame();
frame.setVisible(true);
}
}
|
which produces:

However, this is clearly a pain in the neck to program! There are
better mechanisms, but we won't get to them in this course.
|