java – 获取字体,大小,粗体,等等

前端之家收集整理的这篇文章主要介绍了java – 获取字体,大小,粗体,等等前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法找到访问 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);

解决方法

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

可以在运行时设置大小和样式.

例如.

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

class ShowFonts {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                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((String)value,Font.PLAIN,20);
        label.setFont(font);
        return label;
    }
}

的JavaDoc

GraphicsEnvironment.getAvailableFontFamilyNames()的JDoc部分状态

Returns an array containing the names of all font families in this GraphicsEnvironment localized for the default locale,as returned by Locale.getDefault()..

See also:

07001..

猜你在找的Java相关文章