import java.awt.*;
import java.awt.event.*;
public class Login implements ActionListener
{
Frame frmMain;
Panel pnlMain;
Label lblUser,lblPass,lblInfo;
TextField txtUser,txtPass;
Button btnLogin,btnExit;
public Login()
{
frmMain=new Frame("login");
lblUser=new Label("userName:");
lblPass=new Label("password:");
txtUser=new TextField(16);
txtPass=new TextField(16);
btnLogin=new Button("Login");
btnLogin.addActionListener(this); //为按钮注册监听器
btnExit=new Button("Exit");
btnExit.addActionListener(this); //为按钮注册监听器
lblInfo=new Label("information:");
【1】 //设置Frame布局为4行2列
frmMain.add(lblUser); //添加组件到Frame上
frmMain.add(txtUser);
frmMain.add(lblPass);
frmMain.add(txtPass);
frmMain.add(btnLogin);
frmMain.add(btnExit);
frmMain.add(lblInfo);
frmMain.setSize(300,200);
frmMain.setVisible(true);
}
public static void main(String args[])
{
new Login();
}
//重写actionPerformed方法实现事件监听
public void actionPerformed(ActionEvent e)
{
if( 【2】 ) //如果点击Login按钮
lblInfo.setText("You clicked the login");
if (e.getActionCommand().equals("Exit"))
lblInfo.setText("You clicked the exit");
}
}

答案:【1】frmMain.setLayout(new GridLayout(4,2));,【2】e.getSource()==btnLogin(或e.getActionCommand().equals("Login"))。
小技巧:要获取ActionEvent事件源,可以使用e.getSource()方法,也可以使用e.getActionCommand()方法。前者使用对象名,后者使用对象上的文字。
例11.1.4 应用AWT基本组件MenuBar,Menu,MenuItem和Frame构造应用程序主菜单,程序运行界面如图11-4所示,请在空白处填写合适的语句。
本章节内容来自希赛全国计算机等级考试用书《计算机等级考试考点分析、题解与模拟——二级Java语言》。(购书请见 :http://shop.csai.cn/itbook/itbookinfo.asp?lbbh=10032470)
[1] [2] [3] [4] [5] [6] [7] [8] [9]