- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 多线程
- 示例 - 小应用程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 实用资源
- Java - 快速指南
- Java - 实用资源
如何使用 Java 显示不同字体的文本
问题描述
如何显示不同字体的文本?
解决方案
以下示例演示如何使用 Font 类的 setFont() 方法显示不同字体的文本。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel {
String[] type = { "Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" };
public void paint(Graphics g) {
for (int f = 0; f < type.length; f++) {
for (int s = 0; s < styles.length; s++) {
Font font = new Font(type[f], styles[s], 18);
g.setFont(font);
String name = type[f] + " " + stylenames[s];
g.drawString(name, 20, (f * 4 + s + 1) * 20);
}
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}
结果
上述代码示例将产生以下结果。
Different font names are displayed in a frame.
以下是另一个示例,用于显示不同字体的文本
import java.awt.*;
import javax.swing.*;
public class Main extends JComponent {
String[] dfonts;
Font[] font;
static final int IN = 15;
public Main() {
dfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
font = new Font[dfonts.length];
}
public void paintComponent(Graphics g) {
for (int j = 0; j < dfonts.length; j += 1) {
if (font[j] == null) {
font[j] = new Font(dfonts[j], Font.PLAIN, 16);
}
g.setFont(font[j]);
int p = 15;
int q = 15+ (IN * j);
g.drawString(dfonts[j],p,q);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Different Fonts");
frame.getContentPane().add(new JScrollPane(new Main()));
frame.setSize(350, 650);
frame.setVisible(true);
}
}
java_simple_gui.htm
Advertisement 广告