SWT常用的事件监听器之【SelectionListener】

本文介绍如何在SWT框架中使用SelectionListener监听按钮点击事件,并通过按钮的选中事件展示信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SelectionListener是最常用的事件监听器。

有两个方法:widgetSelected和widgetDefaultSelectd

widgetSelected监听的事件包括:button被单击或组件被选中时。

widgetDefaultSelected监听的事件包括【较少用到的】:文本框回车事件,列表框回车事件

一个按钮单击的例子:

package com.iteye.niewj.swt.chapter1;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class HelloSWT {

	/**
	 * @author niewj
	 * @since 2012-6-1 
	 */
	public static void main(String[] args) {
		Display display = new Display();
		//1.一个窗口
		final Shell shell = new Shell(display);
		shell.setSize(250, 300);
		shell.setText("Hello SWT");
		//2.一个按钮
		Button button = new Button(shell, SWT.NONE);
		button.setText("!点^.^我!");
		button.setLocation(70, 150);
		button.setSize(100,25);

		//3.按钮的选中事件:按钮添加事件
		button.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				MessageDialog.openInformation(shell, "你好", "二B青年");
			}
			
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {}
		});
		
		//4.设置显示
		shell.layout();
		shell.open();
		while(!shell.isDisposed()){
			if(!display.readAndDispatch()){
				display.sleep();
			}
		}
		display.dispose();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值