基于事件的隐式调用风格
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class BtnLabelAction extends Frame implements ActionListener{
//声明窗口类(BtnLabelAction)并实现动作事件接口(ActionListener)
Label prompt;
Button btn;
void CreateWindow(){ //自定义方法
setTitle("MyButton");
prompt = new Label("你好"); //创建标签对象
btn = new Button("操作"); //创建按钮对象
setLayout(new FlowLayout()); //布局设计,用于安排按钮、标签的位置
add(prompt); //将标签放入容器
add(btn); //将按钮放入容器
btn.addActionListener(this); //将监听器(窗体对象本身)注册给按钮对象
setSize(300,100);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//接口ActionListener的事件处理方法
if(e.getSource()==btn) //判断动作事件是否是由按钮btn引发的
if(prompt.getText()=="你好")
prompt.setText("再见");
else
prompt.setText("你好");
}
}
public class BtnTest {
public static void main(String[] args) {
BtnLabelAction bla=new BtnLabelAction();
bla.CreateWindow();
}
}
运行结果:
作业:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.CenterToScreen(); //使窗体自动位于屏幕中央
this.Text = "烟台大学";
button1.Text = "单击该按钮显示系统当前时间";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = (DateTime.Now).ToString();
}
}
}
运行结果: