您的位置:首页 > 编程语言 > Java开发

java 事件监听 - 控件

2016-10-16 03:08 260 查看
java 事件监听

//事件监听
//事件监听,写了一个小案例,点击按钮改变面板的颜色。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Index extends JFrame implements ActionListener{

//设置面板
Wdmb wdmb = new Wdmb();

//设置按钮
JButton anniu1 = new JButton("黄色");
JButton anniu2 = new JButton("红色");

public static void main(String[] args) throws Exception{
//实例化当前类
Index index = new Index();

}

//自动执行
public Index(){

//设置面板的背景色
wdmb.setBackground(Color.yellow);

//添加到界面
this.add(anniu1,BorderLayout.NORTH);
this.add(anniu2,BorderLayout.SOUTH);
this.add(wdmb);

//添加监听事件
anniu1.addActionListener(this);
anniu1.setActionCommand("1");    //区别按钮识别码
anniu2.addActionListener(this);
anniu2.setActionCommand("2");    //区别按钮识别码

this.setSize(500,500);
this.setLocation(300,200);
this.setTitle("绘图");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

//ActionListener 的抽象方法
//ActionEvent e 是固定的
public void actionPerformed(ActionEvent e){

//e.getActionCommand().equals("1") 判断“区别按钮识别码”是否相等

if(e.getActionCommand().equals("1")){
System.out.println("黄色按钮按下了");
wdmb.setBackground(Color.yellow);
}

if(e.getActionCommand().equals("2")){
System.out.println("红色按钮按下了");
wdmb.setBackground(Color.red);
}
}

}

//面板方法
class Wdmb extends JPanel{

//方法覆盖
//JPanel自带方法,下面格式是固定的
//paint 会在三种情况下自动被调用
//1、启动程序  2、窗口大小发生变化时  3、运行repaint函数时
public void paint(Graphics g){
//覆盖父类的方法
super.paint(g);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: