问答题

本题使用下拉菜单来控制字体,窗口中有一个标签和一个下拉菜单,当选中下拉菜单中的任一项字体时,标签上字符串的字体就随之改变。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ComboBoxFrame extends JFrame  {
public ComboBoxFrame(){
setTitle("java2");
setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
style=new JComboBox():
style.setEditable(true);
style.addhem("Serif");
style.addItem("SansSerif");
style.addhem("Monospaced");
style.addhem("Dialog");
style.addhem("Dialoglnput");
style.addActionListener(this);
JPanel p=new JPanel();
P.add(style);
getContentPane().add(p,"South");
panel=new ComboBoxTestPanel();
getContentPane().add(panel,"Center");
}
public void actionPerformed(ActionEvent evt){
JComboBox source=(JComboBox)  ;
String item=(String)source.getSelectedhem():
panel.setStyle(item);
}
private ComboBoxTestPanel panel;
private JComboBox style;
}
class ComboBoxTestPanel extends JPanel{
public ComboBoxTestPanel(){
setStyle("Serif"); }
public void setStyle(String s){
setFont(new Font(S,Font.PLAIN,12));
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
9.drawString("Welcome to China!",0,50);
} }
public class java2{
public static void main(String[]args){
JFrame frame=new ComboBoxFrame();
frame.show();
}
}

【参考答案】

第1处:implements ActionListener
第2处:evt.getSource()
【......

(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)