`

SWT table 中加入事件监听处理

阅读更多
有时需要响应客户点击table的操作.
这时我们可按如下例子为table增加一个监听器.

public class TestTableEvent {
	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		
		// 初始化一个2x2的table
		final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
		table.setLinesVisible(true);
		
		for (int i = 0; i < 2; i++) {
			TableColumn column = new TableColumn(table, SWT.NONE);
			column.setWidth(100);
		}
		
		for (int i = 0; i < 2; i++) {
			TableItem item = new TableItem(table, SWT.NONE);
			item.setText(new String[] { "" + i, "" + i, "" + i });
		}
		
		//为这个table加一个事件,如果点击某一个element,则在控制台显示该element的坐标
		table.addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event event) {
				Point pt = new Point(event.x, event.y);
				int index = table.getTopIndex();
				while (index < table.getItemCount()) {
					final TableItem item = table.getItem(index);
					for (int i = 0; i < table.getColumnCount(); i++) {
						Rectangle rect = item.getBounds(i);
						if (rect.contains(pt)) {
							System.out.println("location : " + index + " : " + i);
						}
					}
					
					index++;
				}
			}
		});
		
		shell.pack();
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}
  • 大小: 7.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics