2017-05-10 1 views
0

J'ai essayé d'implémenter un JComboBox qui contient toutes les familles de polices disponibles, puis j'utilise un programme d'écoute d'action pour modifier la police de ma variable Graphics2D. Je continue à frapper cette exception cependant:Modification de la police Graphics2D de JComboBox

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) 

Pas tout à fait sûr de ce qui va mal. Voici le code pertinent. Merci pour toute aide!

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

Répondre

1

Vous devez créer un objet Font en passant le String dans le constructeur.

Font la classe a un constructeur défini comme public Font(String name,int style,int size).

Vous devez donc changer

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

à

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

Merci !!! @SanketMakani – Jonny1998