Java界面 SWT 开发基础——Display and Shell

本文介绍使用Eclipse SWT创建主窗口及子窗口的方法,包括按钮事件处理、图标设置等,展示了如何通过按钮触发子窗口的创建。

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

Display 基本概述与Shell 类的基本结构

本次实验主要包含创建一个空白的 Display,并在其中建立 Shell 的父类,Shell 中设置按钮,通过按钮创造子窗口。

此外在父窗口设置中加入了图标设置。

代码来自《EclipseSWT/JFace 核心应用》清华大学出版社

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class HelloSWT {

	private static int dialogcnt = 0;				// 用于限制子窗口打开次数
	public static void main(String[] args) {
		
		// chapter 1: 初始化窗口
		Display display = new Display();				// 创建 Display 类的实例		
		final Shell shell = new Shell(display);				// 创建该 Display 的 Shell 类实例
		shell.setText("to SWT");						// 设置窗口标题
		shell.setSize(300, 200);
		shell.setImage(new Image(display, "f:\\icon\\rswt.png"));		// 设置父窗口图标
		//shell.pack();
		shell.open();
		
		
		
		// chapter 2: 向 Shell 中添加 Widget, 用于编写当前 Shell 中放置部件的代码
		Button button = new Button(shell, SWT.CENTER);	// 创建一个按钮
		button.setText("Hello SWT World!");;			// 设置按钮显示的文字
		button.pack();
			// 注册按钮单击事件
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				if(dialogcnt < 3){
					createChildrenShell(shell);				// 创建子窗口
					dialogcnt++;
				}
				
			}
		});
		
		
		// chapter 3: GUI 调用
		//shell.pack();									// 调整布局(保证[窗口]显示正常/适当/恰好)
		//shell.open();									// 打开窗口
		while(!shell.isDisposed()) {
			if(!display.readAndDispatch())
				display.sleep();
		}
		
		// 销毁 Display 实例,释放创建 Display 时获取的内存资源,断开与本地操作系统的连接
		display.dispose();

	}

	// 创建子窗口
	protected static Shell createChildrenShell(Shell shell) {
		Shell dialogShell = new Shell(shell, SWT.CLOSE);
		dialogShell.setText("对话框");
		dialogShell.setSize(shell.getSize());			// 设置窗口大小与原窗口相同
		dialogShell.pack();
		dialogShell.open();
		return dialogShell;
	}

}


坚持,才有水滴石穿的那一天。

如有问题,欢迎各位网友讨论与交流。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值