[说明] 面是一个Applet程序,其功能是有2个按钮,分别为First和Second,以及一个Label控件。要求点击First时则能在Label中显示出Command:First,而点击Second时则能显示出 Command: Second,要求只能使用重载一次actionPerfonned()方法。程序运行结果如图6所示。
import java. awt.*; import java. awt. event. *; import java. applet. *; /* < applet cede = exl_7, class width = 800 height = 400 > </applet > */public class ex]_ extends Applet implements ActionListener { private String str = "ok"; private Label |; private Button btn; public void init( ) { (1) I = new Label(str); I. reshape(10, 10, 150, 30); add(I); (2) btn. reshape(10, 50, 60, 20); (3) add(btn); btn = new Button(" Second" ); btn. reshape(10, 100, 60, 20); (4) btn, addActionListener(this); add(btn);} public void actionPerformed(ActionEvent ae) { str = " Command:" +ae. getActionCommand( ) (5) ex1_7, html< HTML > < HEAD > < TITLE > ext _7 </TITLE > </HEAD > < BODY > < appletcode =" ext. class" width =800 height =400 > </applet > </BODY ></HTML >
参考答案:
解析:(1)setLayout(null); (2)btn=new Button("First"); (3)btn.addActionListener (this); (4)bm. setActionConnnand ("second"); (5)]. setText (str); 本题主要考查Java语言中高级事件ActionEvent和AWT基本构件Label的常用方法的使用。解题关键是熟练掌握动作事件Ac-tionEvent和Label构件的常用方法。在本题中,明确注册的事件监听器是监听按钮的,而不是Label的;调用ActionEvent的setActionConnnand ()方法改变了ActionCommand,使按下第二个按钮时显示Command:second而不是Command: First。调用Label的setText()方法,而不是 Button的方法。