我正在尝试制作一个显示Java中所有可用字体的JComboBox,并将这些字体的名称显示在各自的字体中。该列表似乎在很大程度上起作用,但是相当多的字体要么呈现为巨大的空白空间,要么所有字母都叠加在一起:
我的代码中存在问题,还是操作系统/ Java(Windows 8,JDK 1.7.0_55)?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.*;
public class TextEditor extends JFrame{
private static JPanel j;
private static String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
public TextEditor(){
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setContentPane(j);
setDefaultLookAndFeelDecorated(true);
setTitle("Text Editor");
setVisible(true);
}
public static void main(String[] args) throws FileNotFoundException {
initComponents("Sampe Text");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TextEditor edit = new TextEditor();
}
});
}
public static void initComponents(String s){
j = new JPanel();
j.setLayout(new BorderLayout());
final JComboBox<String> fonts = new JComboBox<String>(fontNames);
fonts.setRenderer(new ListRenderer());
fonts.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
final String font = fonts.getSelectedItem().toString();
fonts.setFont(new Font(font, Font.PLAIN, 16));
}
});
fonts.setPrototypeDisplayValue("XXXXXXXXXXXXXX");
j.add(fonts, BorderLayout.NORTH);
}
private static class ListRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
String selectedIndex = (String) value;
setFont(new Font(selectedIndex, Font.PLAIN, 16));
setText(selectedIndex);
return this;
}
}
}