SWT中树的监听器举例

这个示例展示了如何在SWT环境中创建一个带有树结构的界面,并添加鼠标点击监听器。当用户在树视图上点击时,会更新右侧的Label显示所选节点的数据。

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


import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class SashFormDemo {
	public static void main(String[] args) {
		Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		
		SashForm sashForm = new SashForm(shell,SWT.BORDER|SWT.HORIZONTAL);
		sashForm.setLayout(new FillLayout());
		Composite left = new Composite(sashForm,SWT.NONE);
		left.setLayout(new FillLayout());
		final Tree tree = new Tree(left,SWT.V_SCROLL|SWT.H_SCROLL);
		TreeItem root1 = new TreeItem(tree,SWT.NONE);
		root1.setText("Root");
		root1.setData("root");
			TreeItem root11 = new TreeItem(root1,SWT.NONE);
			root11.setText("Root11");
			root11.setData("11");
			TreeItem root12 = new TreeItem(root1,SWT.NONE);
			root12.setText("Root12");
			root12.setData("12");
		TreeItem root2 = new TreeItem(tree,SWT.NONE);
		root2.setText("Root2");
		root2.setData("2");
				
		Composite right = new Composite(sashForm,SWT.NONE);
		right.setLayout(new FillLayout());
		final Label labR = new Label(right,SWT.NONE);
		labR.setText("Right");
		root1.setExpanded(true);
		 tree.addListener(SWT.MouseUp, new Listener(){

			@Override
			public void handleEvent(Event event) {
				Point point = new Point(event.x,event.y);
				TreeItem item = tree.getItem(point);
				if(item!=null){
				labR.setText((String)(item.getData()));
				}
			}
			
		}); 
		
		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、付费专栏及课程。

余额充值