事件处理程序

完成一个按钮的事件处理程序,实现功能自拟,例如:改变窗口的背景颜色,改变按钮的位置等等。

package test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;     //引入包
public class MyFrame implements ActionListener {
        JFrame f;   //容器      //在方法外声明组件 标签
        JPanel p;   //面板
        JButton b;   //按钮
        JLabel l;    //标签
        public MyFrame() {     //构造方法new所以组件
            f=new JFrame("我的窗口");
            p=new JPanel();
            b=new JButton("click me!");
            l=new JLabel();
            b.addActionListener(this); //按键事件响应
            f.setLocation(40,40); //窗口位置
            f.setSize(400,400);    //窗口大小
            l.setBounds(50,200,80,40); //按键大小
            p.setBackground(Color.orange);  //背景颜色
            p.setLayout(null);  //重置布局
            b.setBounds(100,100,100,100); //按键位置 x,y,宽,高
            f.add(p); //面板加到容器
            p.add(b); //组件加到面板
            p.add(l);
            f.setVisible(true);  //可见
        }
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        new MyFrame();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO 自动生成的方法存根
        l.setText("I coming");    //事件响应后出现的文字
        l.setBounds(50,50,50,50);  //出现的位置
    }

}

代码图

运行结果

posted @ 2019-05-07 21:25  李振业  阅读(136)  评论(0编辑  收藏  举报