2017-05-10 5 views
0

사용 가능한 모든 폰트 패밀리를 가진 JComboBox를 구현 한 다음, 액션 리스너를 사용하여 Graphics2D 변수의 폰트를 변경하려고합니다. 그러나 나는이 예외를 타격 계속 : 무슨 일이 잘못 완전히 확실하지Graphics2D 폰트를 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) 

합니다. 여기에 관련 코드가 있습니다. 어떤 도움을 주셔서 감사합니다!

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

당신은 생성자에서 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*/); 
+1

감사를 변경해야합니다! @SanketMakani – Jonny1998