Java开发GUI之Button控件

Java开发GUI之Button控件

    Java中的awt包提供了丰富的用户界面组件。重要的是,Java的跨平台性使用awt包可以在Windows,MacOS等平台创建桌面软件。本篇博客总结Button控件的简单使用。

package App;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonTest {
	public static void main(String[] args ) {
        //创建面板
		Frame frame = new Frame("BUTTON");
        //创建按钮
		Button button1 = new Button();
        //设置按钮标题
		button1.setLabel("按钮");
        //设置按钮标记 用在触发方法中分区按钮
		button1.setActionCommand("tag1");
        //获取按钮标题
		System.out.println(button1.getLabel());
        //添加按钮
		frame.add(button1);
        //添加交互监听
		button1.addActionListener(new MyActionListener());
		frame.pack();
		frame.show();	
	}
}
class MyActionListener implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
        //这里可以取到按钮设置的actionCommand值
		System.out.println(e.getActionCommand());
	}
}

与addActionCommand方法对应,Button类中还有一些移除监听与获取监听者的方法,如下:

//移除一个监听者
public synchronized void removeActionListener(ActionListener l);
//获取监听者列表
public synchronized ActionListener[] getActionListeners();
//获取监听者列表 泛型数组
public <T extends EventListener> T[] getListeners(Class<T> listenerType);

ActionEvent类中定义了交互行为的一些特征,示例如下:

class MyActionListener implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		//获取触发时间
		System.out.println(e.getWhen());
		//获取触发模式
		System.out.println(e.getModifiers());
		//获取触发事件的控件 此处为Button按钮
		System.out.println(e.getSource());
		//获取关联的actionCommand值
		System.out.println(e.getActionCommand());
	}
}

getModifiers方法获取事件的模式,返回值定义如下:

//按住shift键点击按钮
public static final int SHIFT_MASK          = Event.SHIFT_MASK;
//按住ctrl键点击按钮
public static final int CTRL_MASK           = Event.CTRL_MASK;
//按住meta键点击按钮
public static final int META_MASK           = Event.META_MASK;
//按住alt键点击按钮
public static final int ALT_MASK            = Event.ALT_MASK;

 

转载于:https://my.oschina.net/u/2340880/blog/909693

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值