下面列出了怎么用org.eclipse.swt.widgets.TreeItem的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param pathAsString
*/
private void addTreeItem(String pathAsString) {
if (pathAsString != null && pathAsString.trim().length() > 0) {
// forbid duplicate selections
TreeItem[] items = tree.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getText().equals(pathAsString)) {
return;
}
}
TreeItem item = new TreeItem(tree, 0);
item.setText(pathAsString);
item.setImage(ImageCache.asImage(SharedUiPlugin.getImageCache().get(getImageConstant())));
}
}
/**
* Checks whether this action can be added for the selected element in the call hierarchy.
*
* @return <code> true</code> if the action can be added, <code>false</code> otherwise
*/
protected boolean canActionBeAdded() {
IStructuredSelection selection= (IStructuredSelection)getSelection();
if (selection.isEmpty())
return false;
Iterator<?> iter= selection.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (!(element instanceof MethodWrapper))//takes care of '...' node
return false;
}
TreeItem[] items= fCallHierarchyViewer.getTree().getSelection();
for (int k= 0; k < items.length; k++) {
if (!checkForChildren(items[k]))
return false;
}
return true;
}
private void init( )
{
if ( dimension != null )
{
levelViewer.setInput( dimension );
levelViewer.expandToLevel( dimension.getDefaultHierarchy( )
.getContentCount( IHierarchyModel.LEVELS_PROP ) );
}
if ( showLevels == null || showLevels.size( ) == 0 )
return;
TreeItem item = levelViewer.getTree( ).getItem( 0 );
while ( item != null )
{
LevelHandle level = (LevelHandle) item.getData( );
if ( showLevels.contains( level ) )
{
item.setChecked( true );
}
if ( item.getItemCount( ) > 0 )
item = item.getItem( 0 );
else
item = null;
}
}
/**
* Common parm update.
*
* @param existingTreeItem the existing tree item
* @param existingCP the existing CP
* @param prevName the prev name
*/
private void commonParmUpdate(TreeItem existingTreeItem, ConfigurationParameter existingCP,
String prevName) {
updateParmInSettingsGUI(existingCP, existingTreeItem, prevName);
String newName = existingCP.getName();
if (!newName.equals(prevName)) {
// name changed; update the settings model
ConfigurationParameterSettings cps = getModelSettings();
String[] allGroupNames = new String[] { null };
if (usingGroupsButton.getSelection()) {
allGroupNames = (String[]) Utility
.addElementToArray(getAllGroupNames(), null, String.class);
}
Object value;
for (int i = 0; i < allGroupNames.length; i++) {
if (null != (value = cps.getParameterValue(allGroupNames[i], prevName))) {
cps.setParameterValue(allGroupNames[i], newName, value);
cps.setParameterValue(allGroupNames[i], prevName, null);
}
}
}
}
/**
* Adds the parm.
*
* @param name the name
* @param modelParm the model parm
* @param group the group
* @param override the override
*/
public void addParm(String name, ConfigurationParameter modelParm, ConfigGroup group,
String override) {
TreeItem parentGroup = getTreeItemGroup(group);
AddParameterDialog dialog = new AddParameterDialog(this, group);
dialog.parmName = name;
dialog.description = modelParm.getDescription();
dialog.mandatory = modelParm.isMandatory();
dialog.multiValue = modelParm.isMultiValued();
dialog.parmType = modelParm.getType();
// dialog.overrideSpec = override;
ConfigurationParameter parmInGroup = addNewConfigurationParameter(dialog, parentGroup);
addOverride(parmInGroup, override);
parentGroup.setExpanded(true);
commonActionFinish();
}
/**
* Return the tree path seperated by Const.FILE_SEPARATOR, starting from a certain depth in the tree.
*
* @param ti The TreeItem to get the path for
* @param from The depth to start at, use 0 to get the complete tree.
* @return The tree path.
*/
public static final String getTreePath( TreeItem ti, int from ) {
String[] path = getTreeStrings( ti );
if ( path == null ) {
return null;
}
String retval = "";
for ( int i = from; i < path.length; i++ ) {
if ( !path[ i ].equalsIgnoreCase( Const.FILE_SEPARATOR ) ) {
retval += Const.FILE_SEPARATOR + path[ i ];
}
}
return retval;
}
/**
* Edits the allowed value.
*
* @param item the item
* @param parent the parent
*/
private void editAllowedValue(TreeItem item, TreeItem parent) {
TypeDescription td = getTypeDescriptionFromTableTreeItem(parent);
AllowedValue av = getAllowedValueFromTableTreeItem(item);
AllowedValue localAv = getLocalAllowedValue(td, av); // must use unmodified value of "av"
AddAllowedValueDialog dialog = new AddAllowedValueDialog(this, av);
if (dialog.open() == Window.CANCEL)
return;
allowedValueUpdate(av, dialog);
allowedValueUpdate(localAv, dialog);
if (!valueChanged)
return;
// update the GUI
item.setText(AV_COL, av.getString());
editor.addDirtyTypeName(td.getName());
finishActionPack();
}
private String getToolTip( TreeItem item )
{
Object obj = item.getData( );
if ( obj instanceof TreeData )
{
Object data = ( (TreeData) item.getData( ) ).getWrappedObject( );
if ( data instanceof Field )
{
return ( (Field) data ).getName( )
+ " : " //$NON-NLS-1$
+ ClassParser.getTypeLabel( ( (Field) data ).getGenericType( ) );
}
if ( data instanceof Method )
{
return ( (Method) data ).getName( )
+ "(" //$NON-NLS-1$
+ ClassParser.getParametersLabel( (Method) data )
+ ")" //$NON-NLS-1$
+ " : " + ClassParser.getTypeLabel( ( (Method) data ).getGenericReturnType( ) ); //$NON-NLS-1$
}
return item.getText( );
}
return null;
}
@Override
public boolean performOk() {
final IPreferenceStore store = getPreferenceStore();
store.setValue(PreferenceConstants.ENABLED, enabled.getSelection());
store.setValue(PreferenceConstants.LINE_ALPHA, lineAlpha.getSelection());
store.setValue(PreferenceConstants.LINE_STYLE,
lineStyle.getSelectionIndex() + 1);
store.setValue(PreferenceConstants.LINE_WIDTH, lineWidth.getSelection());
store.setValue(PreferenceConstants.LINE_SHIFT, lineShift.getSelection());
colorFieldEditor.store();
final RGB rgb = colorFieldEditor.getColorSelector().getColorValue();
final Color color = new Color(PlatformUI.getWorkbench().getDisplay(), rgb);
Activator.getDefault().setColor(color);
store.setValue(PreferenceConstants.DRAW_LEFT_END,
drawLeftEnd.getSelection());
store.setValue(PreferenceConstants.DRAW_BLANK_LINE,
drawBlankLine.getSelection());
store.setValue(PreferenceConstants.SKIP_COMMENT_BLOCK,
skipCommentBlock.getSelection());
String types = "";
for (final TreeItem item : contentTypesTree.getItems()) {
types = getContentTypes(item, types);
}
store.setValue(PreferenceConstants.CONTENT_TYPES, types);
return super.performOk();
}
/**
* Alter existing configuration parameter.
*
* @param dialog the dialog
* @param existingTreeItem the existing tree item
*/
private void alterExistingConfigurationParameter(AddParameterDialog dialog,
TreeItem existingTreeItem) {
ConfigurationParameter existingCP = getCorrespondingModelParm(existingTreeItem);
ConfigurationParameter previousCP = existingCP;
previousCP = (ConfigurationParameter) previousCP.clone();
fillModelParm(dialog, existingCP);
fillParmItem(existingTreeItem, existingCP);
// the following may have changed in an existing param spec, that could
// affect the setting:
// 1) the name, 2) the type, 3) the multi-value aspect
// Description or mandatory changes have no effect on the settings
// If the multi-value aspect changes, drop all the settings
// If the type changes, drop all the settings
// If the name changes, change existing settings for that parm name in all groups
if ((!previousCP.getType().equals(existingCP.getType()))
|| (previousCP.isMultiValued() != existingCP.isMultiValued())) {
removeParmSettingFromMultipleGroups(existingTreeItem, !REMOVE_FROM_GUI);
}
commonParmUpdate(existingTreeItem, existingCP, previousCP.getName());
}
/**
* Get an array of strings containing the path from the given TreeItem to the parent.
*
* @param ti
* The TreeItem to look at
* @return An array of string describing the path to the TreeItem.
*/
public static final String[] getTreeStrings( TreeItem ti ) {
int nrlevels = getTreeLevel( ti ) + 1;
String[] retval = new String[nrlevels];
int level = 0;
retval[nrlevels - 1] = ti.getText();
TreeItem parent = ti.getParentItem();
while ( parent != null ) {
level++;
retval[nrlevels - level - 1] = parent.getText();
parent = parent.getParentItem();
}
return retval;
}
private static boolean waitUntilTreeHasItemImpl(SWTBot bot, final TreeItem tree,
final String nodeText) {
try {
bot.waitUntil(new DefaultCondition() {
@Override
public String getFailureMessage() {
return "Could not find node with text " + nodeText;
}
@Override
public boolean test() throws Exception {
return getTreeItem(tree, nodeText) != null;
}
});
} catch (TimeoutException e) {
return false;
}
return true;
}
/**
* remove either a binding or an external resource. Removing the resource removes all bindings
* associated with it
*
*/
private void handleRemove() {
int selectionCount = tree.getSelectionCount();
if (1 != selectionCount)
return;
TreeItem item = tree.getSelection()[0];
if (null == item.getParentItem()) { // case of removing a resource
if (Window.CANCEL == Utility
.popOkCancel("Removing Resource",
"Removing an External Resource and all its bindings. Resource name:"
+ item.getText(), MessageDialog.WARNING))
return;
removeAllBindings(item);
removeResource(item);
} else { // case of removing a binding
removeBinding(item);
}
}
/**
* Export content of a tree to TSV file
* @param tree
* the tree to export
* @param stream
* the output stream
*/
public static void exportTreeToTsv(@Nullable Tree tree, @Nullable OutputStream stream) {
if (tree == null || stream == null) {
return;
}
try (PrintWriter pw = new PrintWriter(stream)) {
int size = tree.getItemCount();
List<String> columns = new ArrayList<>();
for (int i = 0; i < tree.getColumnCount(); i++) {
String valueOf = String.valueOf(tree.getColumn(i).getText());
if (valueOf.isEmpty() && i == tree.getColumnCount() - 1) {
// Linux "feature", an invisible column is added at the end
// with gtk2
break;
}
columns.add(valueOf);
}
String join = Joiner.on('\t').skipNulls().join(columns);
pw.println(join);
for (int i = 0; i < size; i++) {
TreeItem item = tree.getItem(i);
printItem(pw, columns, item);
}
}
}
private void performViewOrCopyCell(Option option) {
try {
MouseEvent event = xViewer.getMouseListener().getLeftClickEvent();
TreeItem item = xViewer.getItemUnderMouseClick(new Point(event.x, event.y));
TreeColumn column = xViewer.getColumnUnderMouseClick(new Point(event.x, event.y));
if (item != null && column != null) {
int columnNum = 0;
for (int x = 0; x < xViewer.getTree().getColumnCount(); x++) {
if (xViewer.getTree().getColumn(x).equals(column)) {
columnNum = x;
break;
}
}
ViewSelectedCellDataAction action = new ViewSelectedCellDataAction(xViewer, clipboard, option);
action.run(column, item, columnNum);
}
} catch (Exception ex) {
// do nothing
}
}
/**
* Handle hover.
*
* @param event the event
*/
public void handleHover(Event event) {
// next getItem call requires that table have SWT.FULL_SELECTION Style
TreeItem item = tt.getItem(new Point(event.x, event.y));
if (null != item) {
Object o = item.getData();
if (null == o)
throw new InternalErrorCDE("invalid state");
if (o instanceof TypeDescription) {
setToolTipText(tt, ((TypeDescription) o).getDescription());
} else if (o instanceof FeatureDescription) {
FeatureDescription fd = (FeatureDescription) o;
if (item.getBounds(MULTIPLE_REF_OK_COL).contains(event.x, event.y)
&& isArrayOrListType(fd.getRangeTypeName())) {
Boolean mra = fd.getMultipleReferencesAllowed();
setToolTipText(tt, (mra != null && mra) ? "Multiple References Allowed"
: "Multiple References Not Allowed");
} else
setToolTipText(tt, fd.getDescription());
} else if (o instanceof AllowedValue) {
setToolTipText(tt, ((AllowedValue) o).getDescription());
}
} else
tt.setToolTipText("");
}
private void selectionHandler(Event event) {
if (event.detail == SWT.CHECK) {
TreeItem item = (TreeItem) event.item;
if (item.getData() instanceof IType) {
IType type = (IType) item.getData();
if (!txtUMLLayout.contains(type)) {
txtUMLLayout.add(type);
} else {
txtUMLLayout.remove(type);
}
updateParentCheck(item.getParentItem());
} else {
checkItems(item, item.getChecked());
}
}
}
@Override
protected void openWindow(final PTWidget widget, final Item item, final PTProperty property) {
final ColorDialog dialog = new ColorDialog(widget.getWidget().getShell());
final RGB result = dialog.open();
if (result != null) {
property.setValue(result);
final Color bgColor = getBackgroundColor(property);
if (bgColor != null) {
if (item instanceof TableItem) {
((TableItem) item).setBackground(1, bgColor);
}
if (item instanceof TreeItem) {
((TreeItem) item).setBackground(1, bgColor);
}
SWTGraphicUtil.addDisposer(item, bgColor);
}
if (item instanceof TableItem) {
((TableItem) item).setText(1, getTextFor(property));
} else {
((TreeItem) item).setText(1, getTextFor(property));
}
}
}
/**
* @see org.eclipse.nebula.widgets.opal.propertytable.editor.PTChooserEditor#openWindow(org.eclipse.nebula.widgets.opal.propertytable.PTWidget,
* org.eclipse.swt.widgets.Item, org.eclipse.nebula.widgets.opal.propertytable.PTProperty)
*/
@Override
protected void openWindow(final PTWidget widget, final Item item, final PTProperty property) {
final DirectoryDialog dialog = new DirectoryDialog(widget.getWidget().getShell());
dialog.setMessage(ResourceManager.getLabel(ResourceManager.CHOOSE_DIRECTORY));
final String result = dialog.open();
if (result != null) {
if (item instanceof TableItem) {
((TableItem) item).setText(1, result);
} else {
((TreeItem) item).setText(1, result);
}
property.setValue(result);
}
}
/**
* Updates the check / gray state of all parent items.
*
* @param item
* the item
*/
private void updateParentItems(final TreeItem item) {
if (item != null) {
final Item[] children = getChildren(item);
boolean containsChecked = false;
boolean containsUnchecked = false;
for (final Item element : children) {
final TreeItem curr = (TreeItem) element;
containsChecked |= curr.getChecked();
containsUnchecked |= (!curr.getChecked() || curr.getGrayed());
}
item.setChecked(containsChecked);
item.setGrayed(containsChecked && containsUnchecked);
updateParentItems(item.getParentItem());
}
}
/**
* If all the leaves in a group are selected the group is also selected
*/
private void setGroupsSelectionIfRequired(Tree tree, List<Integer> columnEntryIndexes){
Collection<TreeItem> allLeaves = ArrayUtil.asCollection(tree.getItems());
Collection<TreeItem> selectedLeaves = ArrayUtil.asCollection(tree.getSelection());
for (TreeItem leaf : allLeaves) {
if(isColumnGroupLeaf(leaf)){
boolean markSelected = true;
Collection<TreeItem> nestedLeaves = ArrayUtil.asCollection(leaf.getItems());
for (TreeItem nestedLeaf : nestedLeaves) {
ColumnEntry columnEntry = getColumnEntryInLeaf(nestedLeaf);
if(!columnEntryIndexes.contains(columnEntry.getIndex())){
markSelected = false;
}
}
if(markSelected){
selectedLeaves.add(leaf);
}
}
}
tree.setSelection(selectedLeaves.toArray(new TreeItem[] {}));
}
private TreeItem createSubFolderItem( TreeItem parent, IClassInfo classInfo )
{
return createSubTreeItem( parent,
classInfo.getDisplayName( ),
IMAGE_FOLDER,
null,
classInfo.getToolTip( ),
true );
}
private void refreshBrowser() {
String filename = wFilename.getText();
if ( StringUtils.isEmpty( filename ) ) {
return;
}
// Browse to the selected file location...
//
try {
activeFileObject = HopVfs.getFileObject( filename );
if ( activeFileObject.isFolder() ) {
activeFolder = activeFileObject;
} else {
activeFolder = activeFileObject.getParent();
}
wBrowser.removeAll();
fileObjectsMap = new HashMap<>();
TreeItem parentFolderItem = new TreeItem( wBrowser, SWT.NONE );
parentFolderItem.setImage( GuiResource.getInstance().getImageFolder() );
parentFolderItem.setText( activeFolder.getName().getBaseName() );
fileObjectsMap.put( getTreeItemPath( parentFolderItem ), activeFolder );
populateFolder( activeFolder, parentFolderItem );
parentFolderItem.setExpanded( true );
} catch ( Throwable e ) {
showError( "Error browsing to location: " + filename, e );
}
}
/**
* Takes an existing model parm and fills a pre-allocated treeItem. 3 callers:
* addNewConfigurationParameter, alterExistingConfigurationParamater (editing), fill (bulk update
* from refresh)
*
* @param item the item
* @param parm the parm
*/
protected void fillParmItem(TreeItem item, ConfigurationParameter parm) {
item.setText(parmGuiString(parm));
// // set data if tree == parmsection tree
// if (item.getParent() == parameterSectionTree)
// back link used to find corresponding model parm decl from tree item
item.setData(parm);
}
private void toggleColumnGroupSelection(TreeItem treeItem) {
if(isColumnGroupLeaf(treeItem)){
Collection<TreeItem> selectedLeaves = ArrayUtil.asCollection(selectedTree.getSelection());
boolean selected = selectedLeaves.contains(treeItem);
if(selected){
selectAllChildren(selectedTree, treeItem);
} else {
unSelectAllChildren(selectedTree, treeItem);
}
}
}
/** {@inheritDoc} */
@Override
protected void setExpanded(final Item item, final boolean expand) {
super.setExpanded(item, expand);
if (expand && item instanceof TreeItem) {
initializeItem((TreeItem) item);
}
}
/**
* Helper method to check whether a given tree is expanded which can be called from any thread.
*/
public static boolean isTreeExpanded(final TreeItem tree) {
return UIThreadRunnable.syncExec(new Result<Boolean>() {
@Override
public Boolean run() {
return tree.getExpanded();
}
});
}
/**
* {@inheritDoc}
*/
@Override
protected void refreshOutlineVisuals() {
final Sequence sequence = (Sequence) getModel();
if (!DBManagerFactory.getDBManager(getDiagram()).isSupported(DBManager.SUPPORT_SEQUENCE)) {
((TreeItem) getWidget()).setForeground(ColorConstants.lightGray);
} else {
((TreeItem) getWidget()).setForeground(ColorConstants.black);
}
setWidgetText(getDiagram().filter(sequence.getName()));
setWidgetImage(ERDiagramActivator.getImage(ImageKey.SEQUENCE));
}
public static void refresh(TreeItem root,Display display,String path){
File fileScript = new File(path);
File files[] = fileScript.listFiles();
for(int i=0;i<files.length;i++){
listFile(files[i],root,display);
}
}
public IJavaProject[] getCheckedProjects() {
ArrayList<Object> res= new ArrayList<Object>();
TreeItem[] treeItems= fInputGroup.getTree().getItems();
for (int i= 0; i < treeItems.length; i++) {
if (treeItems[i].getChecked()) {
Object curr= treeItems[i].getData();
if (curr instanceof IJavaProject) {
res.add(curr);
}
}
}
return res.toArray(new IJavaProject[res.size()]);
}