0
我一直在試圖實現一個JComboBox,其中包含所有可用的字體系列,然後使用動作偵聽器來更改我的Graphics2D變量的字體。然而,我繼續打這個例外:從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);
}
}
謝謝! @SanketMakani – Jonny1998