从JComboBox更改Graphics2D字体

时间:2017-05-10 06:06:40

标签: java fonts jcombobox

我一直在尝试实现一个包含所有可用字体系列的JComboBox,然后使用动作侦听器来更改Graphics2D变量的字体。不过我一直在遇到这个例外:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.awt.Font
at Paint$TextBox$FontListener.actionPerformed(Paint.java:250)

不完全确定出了什么问题。这是相关的代码。谢谢你的帮助!

class TextBox {

    JFrame text = new JFrame("Text Box");
    JTextField TB = new JTextField();
    JLabel tb = new JLabel("                         Type Message: ");

    String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    JComboBox font = new JComboBox(fonts);

    public TextBox() {
        text.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TB.addActionListener(new TextListener());
        font.addActionListener(new FontListener());
        text.setLayout(new GridLayout(0, 2));
        text.add(tb);
        text.add(TB);
        text.add(font);

        text.setSize(400, 75);
        text.setLocation(250, 200);
    }

    public void visible() {
        text.setVisible(true);
    }

    class TextListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            yourText = (String)TB.getText();
        }   
    }   

    class FontListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {                
            JComboBox selectedFont = (JComboBox)e.getSource();
            Font newFont =  (Font)selectedFont.getSelectedItem();
            Font derivedFont = newFont.deriveFont(newFont.getSize()*1.4F);
            graphics.setFont(derivedFont);
        }
    }

1 个答案:

答案 0 :(得分:1)

您需要通过在构造函数中传递Font来创建String对象。

Font 类的构造函数定义为public Font(String name,int style,int size)

所以你需要改变

Font newFont = (Font)selectedFont.getSelectedItem();

Font newFont = new Font((String)selectedFont.getSelectedItem() , /*style*/ , /*size*/);