我有一个treeViewer,我必须在其上实现编辑以进行重命名,应该能够以两种方式调用它:
- 用F2钥匙
如果选择了节点,则单击鼠标。
更何况 Windows 允许重命名文件夹。 为此,我使用
ICellModifier
了 ,但没有给出预期的结果。
通过以下代码,我已经实现了第 2 点,尽管如果选择了一个节点,它会在双击打开编辑器时产生问题。主要关注的是允许F2重命名的密钥仍然悬而未决。我必须在 keyListener 中使用我在下面编写的相同代码,但它不起作用......我真的不认为下面的代码是一个优化的解决方案,但它可以工作。对于第二个选项,是否有允许F2重命名密钥的解决方案以及如何优化以下代码?
tree.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event event)
{
final TreeItem item = (TreeItem)event.item;
if (item != null && item == lastItem[0])
{
boolean showBorder = true;
//it will not allow to rename root
if (item.getParentItem() == null)
return;
final Composite composite = new Composite(tree, SWT.NONE);
if (showBorder)
composite.setBackground(black);
final Text text = new Text(composite, SWT.NONE);
final int inset = showBorder ? 1 : 0;
composite.addListener(SWT.Resize, new Listener()
{
public void handleEvent(Event e)
{
Rectangle rect = composite.getClientArea();
text.setBounds(rect.x + inset, rect.y + inset,
rect.width - inset * 2, rect.height - inset * 2);
}
});
textListener = new Listener()
{
boolean focusOutOnce = false;
public void handleEvent(final Event e)
{
String newText ;
Model data = (Model)item.getData();
boolean caseType = false;
//if nodeType is case
if(data.getNodeType() == Model.TestType.CASE)
caseType = true;
String oldText = item.getText();
switch (e.type)
{
case SWT.FocusOut:
//validate the renamed text and update
//model to get dump in to file.
newText = text.getText();
if(Utils.length(newText) != 0)
newText = newText.trim();
if(!focusOutOnce && newText.equals(oldText))
{
item.setText(newText);
composite.dispose();
break;
}
if (!focusOutOnce &&
(Model.containsAction(newText) || Model.containsCase(newText) ) )
{
composite.dispose();
break;
}
if (!focusOutOnce )
{
//action edit name
}
else if(!focusOutOnce)
{
}
composite.dispose();
break;
case SWT.Verify:
newText = text.getText();
String leftText = newText.substring(0, e.start);
String rightText =
newText.substring(e.end,
newText.length());
GC gc = new GC(text);
Point size =
gc.textExtent(leftText + e.text
+ rightText);
gc.dispose();
size = text.computeSize(size.x, SWT.DEFAULT);
editor.horizontalAlignment = SWT.LEFT;
Rectangle itemRect = item.getBounds(),
rect = tree.getClientArea();
editor.minimumWidth =
Math.max(size.x, itemRect.width)
+ inset * 2;
int left = itemRect.x,
right = rect.x + rect.width;
editor.minimumWidth =
Math.min(editor.minimumWidth, right
- left);
editor.minimumHeight = size.y + inset * 2;
editor.layout();
break;
case SWT.Traverse:
switch (e.detail)
{
case SWT.TRAVERSE_RETURN:
composite.dispose();
break;
case SWT.TRAVERSE_ESCAPE:
composite.dispose();
e.doit = false;
}
break;
}
}
};
text.addListener(SWT.Verify, textListener);
text.addListener(SWT.Traverse, textListener);
text.addListener(SWT.FocusOut, textListener);
editor.setEditor(composite, item);
text.setText(item.getText());
text.selectAll();
text.setFocus();
}
lastItem[0] = item;
}
});