Jonny1998
Jonny1998

Reputation: 107

Changing Graphics2D font from JComboBox

I've been trying to implement a JComboBox that has all of the available font families in it and then using an action listener to change the font of my Graphics2D variable. I keep hitting this exception however:

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)

Not entirely sure what is going wrong. Here is the pertinent code. Thanks for any help!

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);
        }
    }

Upvotes: 0

Views: 81

Answers (1)

Sanket Makani
Sanket Makani

Reputation: 2489

You need to create a Font object by passing the String in the constructor.

Font class has a constructor defined as public Font(String name,int style,int size).

So you need to change

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

to

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

Upvotes: 1

Related Questions