【问题标题】:Changing Graphics2D font from JComboBox从 JComboBox 更改 Graphics2D 字体
【发布时间】:2017-05-10 06:06:39
【问题描述】:

我一直在尝试实现一个包含所有可用字体系列的 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);
        }
    }

【问题讨论】:

    标签: java fonts jcombobox


    【解决方案1】:

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

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

    所以你需要改变

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2012-08-20
      • 2016-03-16
      • 2020-07-04
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多