获取字体、大小、加粗等信息

11

我在查找如何访问Windows字体或预定义字体和大小方面遇到了麻烦。所以对于我的Java程序,我有一个带有字体、大小和颜色的JComboBox。问题是我需要预先输入字体、大小和颜色。如何获取预定义的字体、颜色和大小?目前为止,这是我针对此字体所拥有的,但它不正确。

               if (font.equals("Arial")) {

                if (size.equals("8")) {
                    setSize = 8;
                } else if (size.equals("10")) {
                    setSize = 10;
                } else if (size.equals("12")) {
                    setSize = 12;
                }

                if (color.equals("Black")) {
                    setColor = Color.BLACK;
                } else if (color.equals("Blue")) {
                    setColor = Color.BLUE;
                } else if (color.equals("Red")) {
                    setColor = Color.red;
                }

                Font font = new Font("Arial", setAttribute, setSize);
                Writer.setFont(font);
                Writer.setForeground(setColor);

1
我在寻找访问Windows字体或预定义字体的相关信息方面遇到了困难。如果只针对Windows,为什么要使用Java编码呢?在Mac和*nix系统上可能会遇到麻烦。 - Andrew Thompson
这只是一个练习,有人让我做的,并不是一个完整的应用程序,只是想学习一些东西。 - Jazzy
1个回答

20
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();

大小和风格可以在运行时设置。

例如

字体选择器

import java.awt.*;
import javax.swing.*;

public class ShowFonts {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fonts = ge.getAvailableFontFamilyNames();
            JComboBox fontChooser = new JComboBox(fonts);
            fontChooser.setRenderer(new FontCellRenderer());
            JOptionPane.showMessageDialog(null, fontChooser);
        });
    }
}

class FontCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        JLabel label = (JLabel)super.getListCellRendererComponent(
                list,value,index,isSelected,cellHasFocus);
        Font font = new Font(value.toString(), Font.PLAIN, 20);
        label.setFont(font);
        return label;
    }
}

JavaDoc

GraphicsEnvironment.getAvailableFontFamilyNames()的JDoc部分说明如下:

返回包含所有本地化为默认语言环境(由Locale.getDefault()返回)的字体系列名称的数组,该名称在此GraphicsEnvironment中可用。

另请参见:

getAllFonts()..


1
哇,这正是我在寻找的。所以GraphicsEnvironment获取了您的系统正在运行的字体类型? - Jazzy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接