论坛首页 Java企业应用论坛

学习定制表格树的项(二)

浏览 2139 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-08-11  

表格和树的项只可以有一个图像,而且这个图像只能够画在图像的前面。

学习了定制表格和树的项后,觉得前面也可以定制多个图像了。

 

例子:

public class Snippet300 {
	private static int IMAGE_MARGIN = 2;
	private static Image xImage;
	private static Display display;

	public static void main(String [] args) {
		display = new Display();
		Shell shell = new Shell(display);
		shell.setBounds(10, 10, 350, 200);
		createImage();
		final Tree tree = new Tree(shell, SWT.CHECK);
		tree.setBounds(10, 10, 300, 150);
		TreeItem item = new TreeItem(tree, SWT.NONE);
		item.setImage(xImage);
		item.setText("root item");
		for (int i = 0; i < 4; i++) {
			TreeItem newItem = new TreeItem(item, SWT.NONE);
			newItem.setText("descendent " + i);
			//			if (i % 2 == 0) {
			//				newItem.setData(xImage);
			//			}
			newItem.setImage(xImage);
			item.setExpanded(true);
			item = newItem;
		}
		treeAddListener(tree);

		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) display.sleep();
		}
		xImage.dispose();
		display.dispose();
	}

	private static void createImage() {
		xImage = new Image (display, 16, 16);
		GC gc = new GC(xImage);
		gc.setForeground(display.getSystemColor(SWT.COLOR_RED));
		gc.drawLine(1, 1, 14, 14);
		gc.drawLine(1, 14, 14, 1);
		gc.drawOval(2, 2, 11, 11);
		gc.dispose();
	}

	private static void treeAddListener(final Tree tree) {
		Listener listener = new Listener() {
			public void handleEvent(Event event) {
				TreeItem item = (TreeItem)event.item;
				Image image = (Image)item.getImage();
				switch(event.type) {
				case SWT.MeasureItem:
				{
					if (image == null) break;
					event.width += 2*(image.getBounds().width + IMAGE_MARGIN);
					break;
				}
				case SWT.EraseItem:
				{
					event.detail &= ~SWT.FOREGROUND;
					break;
				}
				case SWT.PaintItem:
				{
					if (image == null) break;
					int x,y;
					int itemH = tree.getItemHeight();
					int imageH = image.getBounds().height;
					int imageW = image.getBounds().width;

					// draw the 1 image
					x = event.x ;
					y = event.y + (itemH - imageH)/2;
					event.gc.drawImage(image, x, y);

					// draw the 2 image
					x += IMAGE_MARGIN + imageW;
					event.gc.drawImage(image, x, y);

					// draw the string
					String text = item.getText();
					x += IMAGE_MARGIN + imageW;
					y = event.y+2;
					event.gc.drawText(text, x, y);

					// draw the 3 image
					x += event.width - imageW;
					y = event.y + (itemH - imageH)/2;
					event.gc.drawImage(image, x, y);
					break;
				}
				}
			}
		};

		tree.addListener(SWT.MeasureItem, listener);
		tree.addListener(SWT.EraseItem, listener);
		tree.addListener(SWT.PaintItem, listener);
	}
}

 

改例子,仿照snippet220写的,运行效果,如图:



 

 

  • 大小: 12.7 KB
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics