如何使用swt.TabItem添加关闭按钮?

TabFolder tabFolder = new TabFolder(composite, SWT.CLOSE); TabItem tab1 = new TabItem(tabFolder, SWT.CLOSE); tab1.setText("Tab 1"); TabItem tab2 = new TabItem(tabFolder, SWT.CLOSE); tab2.setText("Tab 2"); 

我有一个swt.TabFolder,它上面有一些swt.TabItems。 我希望有一个关闭按钮与那些TabItems所以我可以关闭我想要的运行时选项卡。 我不想使用CTabFolder或CTabItem

谁能告诉我,我能为此目的做些什么?

 public DomainUI(Composite composite, TabFolder newTabFolder, boolean comingFromSelf) { boolean itemsDisposed = false; TabItem[] itemsOnTabFolder = newTabFolder.getItems(); String[] namesOfItemsOnTabFolder = new String[itemsOnTabFolder.length]; if(comingFromSelf) // checking when to dispose other tabs { if(itemsOnTabFolder.length != 0) { for(int i=0; i= item.getBounds().x + image.getBounds().x && eventLocation.x = item.getBounds().y + image.getBounds().y && eventLocation.y <= item.getBounds().y + image.getBounds().y + image.getBounds().height) { System.out.println("Close tab"); item.dispose(); } else { System.out.println("Don't close tab"); } } }); } 

TabItem没有此function(它将忽略您使用的SWT.CLOSE样式)。 没有其他方式(我知道)而不是使用CTabItem而使用样式SWT.CLOSE 。 您还必须将TabFolder替换为CTabFolder

有关示例,请参阅此页面或此页面。

或者 ,如果您不能离开TabItem ,可以使用item.setImage(xImage);x图像添加到每个选项卡item.setImage(xImage); 并在文件夹中添加一个Listener ,处理“关闭内容”。 当然, x项目将在左侧,而不是右侧……

管理以使其工作。 只需用你的close图像替换img/x.gif (对于测试,你可以使用: display.getSystemImage(SWT.ICON_ERROR) ):

 public static void main(String[] args) { Display display = Display.getDefault(); final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); final TabFolder folder = new TabFolder(shell, SWT.NONE); TabItem item = new TabItem(folder, SWT.NONE); item.setImage(Images.loadImage("img/x.gif")); item.setText("Text"); TabItem item2 = new TabItem(folder, SWT.NONE); item2.setImage(Images.loadImage("img/x.gif")); item2.setText("Text2"); folder.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent arg0) { TabFolder curFolder = (TabFolder)arg0.widget; Point eventLocation = new Point(arg0.x, arg0.y); TabItem item = curFolder.getItem(eventLocation); if(item == null) return; Image image = item.getImage(); // check if click is on image if( eventLocation.x >= item.getBounds().x + image.getBounds().x && eventLocation.x <= item.getBounds().x + image.getBounds().x + image.getBounds().width && eventLocation.y >= item.getBounds().y + image.getBounds().y && eventLocation.y <= item.getBounds().y + image.getBounds().y + image.getBounds().height) { System.out.println("Close tab"); item.dispose(); } else { System.out.println("Don't close tab"); } } @Override public void mouseDown(MouseEvent arg0) { } @Override public void mouseDoubleClick(MouseEvent arg0) { } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } 

结果如下:

关闭前:

在结束之前

关闭后:

关闭后