0

フォント、スタイル、サイズ、ボタンのJTextArea3つでフォントを変更しようとしています。JComboBoxesユーザーは から必要なオプションを選択し、JComboBoxes[OK] をクリックします。ActionListenerOKボタンはこちら

final JDialog dialog = new JDialog();
JPanel  dpanel = new JPanel();
dialog.add(dpanel);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = ge.getAvailableFontFamilyNames();    

JLabel label = new JLabel("         Font                                     Size                   Style");
dpanel.add(label);

final JComboBox font,style,size;
font = new JComboBox(fontnames);
dpanel.add(font);

style = new JComboBox();
style.addItem("Bold");
style.addItem("Italic");
style.addItem("Bold and Italic");
style.addItem("Plain");
dpanel.add(style);

size = new JComboBox();
for(int i=0;i<=100;i++)
{
    size.addItem(i);
}
size.setSelectedItem("22");
dpanel.add(size);

JButton button = new JButton("Done");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
    String fontvalue = (String) font.getSelectedItem();
    int stylevalue = (Integer) style.getSelectedItem();
    int sizevalue = (Integer) size.getSelectedItem();

    if(style.getSelectedItem().equals("Bold"))
    {
        stylevalue = Font.BOLD;
    }
    else if(style.getSelectedItem().equals("Italic"))
    {
        stylevalue = Font.ITALIC;
    }
    else if(style.getSelectedItem().equals("Bold and Italic"))
    {
        stylevalue = Font.BOLD|Font.ITALIC;
    }
    else
    {
        stylevalue = Font.PLAIN;
    }
    Font areafont = new Font(fontvalue,stylevalue,sizevalue);
    area.setFont(areafont);
    dialog.dispose();        
}
});
dpanel.add(button);
dialog.setTitle("Fonts");
dialog.setSize(400,200);
dialog.setLocation(400,200);
dialog.setVisible(true);
dialog.setResizable(false);

うまく動かないので助けてください。例外をスローしますException in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer.

前もって感謝します!

4

4 に答える 4

1

スタイルを次のように定義します

style = new JComboBox();
style.addItem("Bold");
style.addItem("Italic");
style.addItem("Bold and Italic");
style.addItem("Plain");

しかし、あなたは値を取得しています

int stylevalue = (Integer) style.getSelectedItem();

getSelectedItemStringキャストできない値を返しますint

とにかく戻り値を無視してその結果を計算しているように見えるので、これはまったく奇妙です

于 2013-10-01T10:38:30.080 に答える
0

sizeValue は文字列であり、整数にキャストしています。それが例外の理由です。修正してください。

于 2013-10-01T10:37:07.860 に答える
0

Javaドキュメントから

public Object getSelectedItem()

Returns the current selected item.

If the combo box is editable, then this value may not have been added to the combo box with addItem, insertItemAt or the data constructors.

Returns:
    the current selected Object

コードのこの行 int stylevalue = (Integer) style.getSelectedItem();で、例外をスローしている String を int にキャストしようとしています

于 2013-10-01T10:39:41.950 に答える