我在查找有关访问 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.*;
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;
}
}
Java文档
GraphicsEnvironment.getAvailableFontFamilyNames()
的 JDoc部分陈述..
Returns an array containing the names of all font families in this
GraphicsEnvironment
localized for the default locale, as returned byLocale.getDefault()
..
See also:
关于java - 获取字体、大小、粗体等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965038/