Java/SWT JFace Eclipse/Tree
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Bookmark Organizer
- 2 Category Tree
- 3 Create a SWT tree (lazy)
- 4 Create a tree
- 5 Demonstrates CheckboxTreeViewer
- 6 Demonstrates TableTree
- 7 Demonstrates TreeEditor
- 8 Demonstrates TreeViewer
- 9 Detect a selection or check event in a tree (SWT.CHECK)
- 10 Detect Mouse Down In SWT Tree Item
- 11 Displays a single-selection tree, a multi-selection tree, and a checkbox tree
- 12 Insert a SWT tree item (at an index)
- 13 Limit selection to items that match a pattern in SWT Tree
- 14 Print selected items in a SWT tree
- 15 Simple Tree
- 16 SWT Tree
- 17 SWT Tree Composite
- 18 SWT Tree Simple Demo
- 19 SWT Tree With Multi columns
- 20 Tree Example
- 21 Tree Example 2
Bookmark Organizer
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-4-27 16:53:36 by JACK $Id$
*
******************************************************************************/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* Represents a bookmark.
*
*/
class Bookmark {
public String name;
public String href;
public String addDate;
public String lastVisited;
public String lastModified;
}
public class BookmarkOrganizer {
private static String folderLinePrefix = "<DT><H3 FOLDED";
private static String urlLinePrefix = "<DT>\n");
}
}
/**
* Loads the bookmarks from the specified file.
* @param file
* @param rootItem
*/
private void loadBookmark(File file, TreeItem rootItem) {
TreeItem parent = rootItem;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith(folderLinePrefix)) { // a folder.
Matcher matcher = folderPattern.matcher(line);
if (matcher.find()) {
String addDate = matcher.group(1);
String name = matcher.group(2);
TreeItem item = new TreeItem(parent, SWT.NULL);
item.setText(name);
item.setData(KEY_ADD_DATE, addDate);
item.setImage(iconFolder);
parent = item;
}
} else if (line.startsWith(urlLinePrefix)) { // a url
Matcher matcher = urlPattern.matcher(line);
if (matcher.find()) {
Bookmark bookmark = new Bookmark();
bookmark.href = matcher.group(1);
bookmark.addDate = matcher.group(2);
bookmark.lastVisited = matcher.group(3);
bookmark.lastModified = matcher.group(4);
bookmark.name = matcher.group(5);
TreeItem item = new TreeItem(parent, SWT.NULL);
item.setText(bookmark.name);
item.setData(bookmark);
item.setImage(iconURL);
}
} else if (line.equals("</DL><p>")) { // folder boundry.
parent = parent.getParentItem();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setStatus(String message) {
label.setText(message);
}
public static void main(String[] args) {
new BookmarkOrganizer();
}
}
class BookmarkTransfer extends ByteArrayTransfer {
private static final String BOOKMARK_TRANSFER_NAME = "BOOKMARK";
private static final int BOOKMARK_TRANSFER_ID =
registerType(BOOKMARK_TRANSFER_NAME);
private static final BookmarkTransfer instance = new BookmarkTransfer();
public static BookmarkTransfer getInstance() {
return instance;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.Transfer#getTypeIds()
*/
protected int[] getTypeIds() {
return new int[] { BOOKMARK_TRANSFER_ID };
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.Transfer#getTypeNames()
*/
protected String[] getTypeNames() {
return new String[] { BOOKMARK_TRANSFER_NAME };
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.Transfer#javaToNative(java.lang.Object,
* org.eclipse.swt.dnd.TransferData)
*/
protected void javaToNative(Object object, TransferData transferData) {
if (object == null || !(object instanceof Bookmark))
return;
Bookmark bookmark = (Bookmark) object;
if (isSupportedType(transferData)) {
try {
// Writes data to a byte array.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(stream);
out.writeUTF(bookmark.name);
out.writeUTF(bookmark.href);
out.writeUTF(bookmark.addDate);
out.writeUTF(bookmark.lastVisited);
out.writeUTF(bookmark.lastModified);
out.close();
super.javaToNative(stream.toByteArray(), transferData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.Transfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
*/
protected Object nativeToJava(TransferData transferData) {
if (isSupportedType(transferData)) {
byte[] raw = (byte[]) super.nativeToJava(transferData);
if (raw == null)
return null;
Bookmark bookmark = new Bookmark();
try {
ByteArrayInputStream stream = new ByteArrayInputStream(raw);
DataInputStream in = new DataInputStream(stream);
bookmark.name = in.readUTF();
bookmark.href = in.readUTF();
bookmark.addDate = in.readUTF();
bookmark.lastVisited = in.readUTF();
bookmark.lastModified = in.readUTF();
in.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return bookmark;
} else {
return null;
}
}
}
Category Tree
/******************************************************************************
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* All right reserved.
*
* Created on Dec 28, 2003 7:56:40 PM by JACK
* $Id$
*
* visit: http://www.asprise.ru/swt
*****************************************************************************/
import java.util.Vector;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class CategoryTree {
Display display = new Display();
Shell shell = new Shell(display);
final Tree tree = new Tree(shell, SWT.BORDER);
Vector categories = new Vector();
public CategoryTree() {
Category category = new Category("Java libraries", null);
categories.add(category);
category = new Category("UI Toolkits", category);
new Category("AWT", category);
new Category("Swing", category);
new Category("SWT/JFace", category);
category = new Category("Java IDEs", null);
categories.add(category);
new Category("Eclipse", category);
new Category("JBuilder", category);
}
/**
* Builds up the tree with traditional approach.
*
*/
public void traditional() {
for(int i=0; categories != null && i < categories.size(); i++) {
Category category = (Category)categories.elementAt(i);
addCategory(null, category);
}
}
/**
* Adds a category to the tree (recursively).
* @param parentItem
* @param category
*/
private void addCategory(TreeItem parentItem, Category category) {
TreeItem item = null;
if(parentItem == null)
item = new TreeItem(tree, SWT.NONE);
else
item = new TreeItem(parentItem, SWT.NONE);
item.setText(category.getName());
Vector subs = category.getSubCategories();
for(int i=0; subs != null && i < subs.size(); i++)
addCategory(item, (Category)subs.elementAt(i));
}
/**
* Builds up the tree with MVC approach.
*
*/
public void MVC() {
TreeViewer treeViewer = new TreeViewer(tree);
treeViewer.setContentProvider(new ITreeContentProvider() {
public Object[] getChildren(Object parentElement) {
Vector subcats = ((Category)parentElement).getSubCategories();
return subcats == null ? new Object[0] : subcats.toArray();
}
public Object getParent(Object element) {
return ((Category)element).getParent();
}
public boolean hasChildren(Object element) {
return ((Category)element).getSubCategories() != null;
}
public Object[] getElements(Object inputElement) {
if(inputElement != null && inputElement instanceof Vector) {
return ((Vector)inputElement).toArray();
}
return new Object[0];
}
public void dispose() {
//
}
public void inputChanged(Viewer viewer,
Object oldInput,
Object newInput) {
//
}
});
treeViewer.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
return ((Category)element).getName();
}
});
treeViewer.setInput(categories);
}
public void show() {
tree.setSize(300, 200);
shell.setSize(300, 200);
shell.open();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args) {
CategoryTree tree = new CategoryTree();
//tree.traditional();
tree.MVC();
tree.show();
}
/**
* Represents a category of items.
* The max level of categories is 2 only.
*
*/
class Category {
private String name;
private Vector subCategories;
private Category parent;
public Category(String name, Category parent) {
this.name = name;
this.parent = parent;
if(parent != null)
parent.addSubCategory(this);
}
public Vector getSubCategories() {
return subCategories;
}
private void addSubCategory(Category subcategory) {
if(subCategories == null)
subCategories = new Vector();
if(! subCategories.contains(subcategory))
subCategories.add(subcategory);
}
public String getName() {
return name;
}
public Category getParent() {
return parent;
}
}
}
Create a SWT tree (lazy)
/*
* Tree example snippet: create a tree (lazy)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet8 {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Lazy Tree");
shell.setLayout(new FillLayout());
final Tree tree = new Tree(shell, SWT.BORDER);
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
TreeItem root = new TreeItem(tree, 0);
root.setText(roots[i].toString());
root.setData(roots[i]);
new TreeItem(root, 0);
}
tree.addListener(SWT.Expand, new Listener() {
public void handleEvent(final Event event) {
final TreeItem root = (TreeItem) event.item;
TreeItem[] items = root.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getData() != null)
return;
items[i].dispose();
}
File file = (File) root.getData();
File[] files = file.listFiles();
if (files == null)
return;
for (int i = 0; i < files.length; i++) {
TreeItem item = new TreeItem(root, 0);
item.setText(files[i].getName());
item.setData(files[i]);
if (files[i].isDirectory()) {
new TreeItem(item, 0);
}
}
}
});
Point size = tree.ruputeSize(300, SWT.DEFAULT);
int width = Math.max(300, size.x);
int height = Math.max(300, size.y);
shell.setSize(shell.ruputeSize(width, height));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Create a tree
/*
* Tree example snippet: create a tree
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet15 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
final Tree tree = new Tree(shell, SWT.BORDER);
tree.setSize(100, 100);
shell.setSize(200, 200);
for (int i = 0; i < 4; i++) {
TreeItem iItem = new TreeItem(tree, 0);
iItem.setText("TreeItem (0) -" + i);
for (int j = 0; j < 4; j++) {
TreeItem jItem = new TreeItem(iItem, 0);
jItem.setText("TreeItem (1) -" + j);
for (int k = 0; k < 4; k++) {
TreeItem kItem = new TreeItem(jItem, 0);
kItem.setText("TreeItem (2) -" + k);
for (int l = 0; l < 4; l++) {
TreeItem lItem = new TreeItem(kItem, 0);
lItem.setText("TreeItem (3) -" + l);
}
}
}
}
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Demonstrates CheckboxTreeViewer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This class demonstrates the CheckboxTreeViewer
*/
public class CheckFileTree extends FileTree {
/**
* Configures the shell
*
* @param shell
* the shell
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Check File Tree");
}
/**
* Creates the main window"s contents
*
* @param parent
* the main window
* @return Control
*/
protected Control createContents(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
// Add a checkbox to toggle whether the labels preserve case
Button preserveCase = new Button(composite, SWT.CHECK);
preserveCase.setText("&Preserve case");
// Create the tree viewer to display the file tree
final CheckboxTreeViewer tv = new CheckboxTreeViewer(composite);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput("root"); // pass a non-null that will be ignored
// When user checks the checkbox, toggle the preserve case attribute
// of the label provider
preserveCase.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
boolean preserveCase = ((Button) event.widget).getSelection();
FileTreeLabelProvider ftlp = (FileTreeLabelProvider) tv
.getLabelProvider();
ftlp.setPreserveCase(preserveCase);
}
});
// When user checks a checkbox in the tree, check all its children
tv.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
// If the item is checked . . .
if (event.getChecked()) {
// . . . check all its children
tv.setSubtreeChecked(event.getElement(), true);
}
}
});
return composite;
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new CheckFileTree().run();
}
}
/**
* This class demonstrates TreeViewer. It shows the drives, directories, and
* files on the system.
*/
class FileTree extends ApplicationWindow {
/**
* FileTree constructor
*/
public FileTree() {
super(null);
}
/**
* Runs the application
*/
public void run() {
// Don"t return from open() until window closes
setBlockOnOpen(true);
// Open the main window
open();
// Dispose the display
Display.getCurrent().dispose();
}
/**
* Configures the shell
*
* @param shell
* the shell
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
// Set the title bar text and the size
shell.setText("File Tree");
shell.setSize(400, 400);
}
/**
* Creates the main window"s contents
*
* @param parent
* the main window
* @return Control
*/
protected Control createContents(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
// Add a checkbox to toggle whether the labels preserve case
Button preserveCase = new Button(composite, SWT.CHECK);
preserveCase.setText("&Preserve case");
// Create the tree viewer to display the file tree
final TreeViewer tv = new TreeViewer(composite);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput("root"); // pass a non-null that will be ignored
// When user checks the checkbox, toggle the preserve case attribute
// of the label provider
preserveCase.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
boolean preserveCase = ((Button) event.widget).getSelection();
FileTreeLabelProvider ftlp = (FileTreeLabelProvider) tv
.getLabelProvider();
ftlp.setPreserveCase(preserveCase);
}
});
return composite;
}
}
/**
* This class provides the content for the tree in FileTree
*/
class FileTreeContentProvider implements ITreeContentProvider {
/**
* Gets the children of the specified object
*
* @param arg0
* the parent object
* @return Object[]
*/
public Object[] getChildren(Object arg0) {
// Return the files and subdirectories in this directory
return ((File) arg0).listFiles();
}
/**
* Gets the parent of the specified object
*
* @param arg0
* the object
* @return Object
*/
public Object getParent(Object arg0) {
// Return this file"s parent file
return ((File) arg0).getParentFile();
}
/**
* Returns whether the passed object has children
*
* @param arg0
* the parent object
* @return boolean
*/
public boolean hasChildren(Object arg0) {
// Get the children
Object[] obj = getChildren(arg0);
// Return whether the parent has children
return obj == null ? false : obj.length > 0;
}
/**
* Gets the root element(s) of the tree
*
* @param arg0
* the input data
* @return Object[]
*/
public Object[] getElements(Object arg0) {
// These are the root elements of the tree
// We don"t care what arg0 is, because we just want all
// the root nodes in the file system
return File.listRoots();
}
/**
* Disposes any created resources
*/
public void dispose() {
// Nothing to dispose
}
/**
* Called when the input changes
*
* @param arg0
* the viewer
* @param arg1
* the old input
* @param arg2
* the new input
*/
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
// Nothing to change
}
}
/**
* This class provides the labels for the file tree
*/
class FileTreeLabelProvider implements ILabelProvider {
// The listeners
private List listeners;
// Images for tree nodes
private Image file;
private Image dir;
// Label provider state: preserve case of file names/directories
boolean preserveCase;
/**
* Constructs a FileTreeLabelProvider
*/
public FileTreeLabelProvider() {
// Create the list to hold the listeners
listeners = new ArrayList();
// Create the images
try {
file = new Image(null, new FileInputStream("images/file.gif"));
dir = new Image(null, new FileInputStream("images/directory.gif"));
} catch (FileNotFoundException e) {
// Swallow it; we"ll do without images
}
}
/**
* Sets the preserve case attribute
*
* @param preserveCase
* the preserve case attribute
*/
public void setPreserveCase(boolean preserveCase) {
this.preserveCase = preserveCase;
// Since this attribute affects how the labels are computed,
// notify all the listeners of the change.
LabelProviderChangedEvent event = new LabelProviderChangedEvent(this);
for (int i = 0, n = listeners.size(); i < n; i++) {
ILabelProviderListener ilpl = (ILabelProviderListener) listeners
.get(i);
ilpl.labelProviderChanged(event);
}
}
/**
* Gets the image to display for a node in the tree
*
* @param arg0
* the node
* @return Image
*/
public Image getImage(Object arg0) {
// If the node represents a directory, return the directory image.
// Otherwise, return the file image.
return ((File) arg0).isDirectory() ? dir : file;
}
/**
* Gets the text to display for a node in the tree
*
* @param arg0
* the node
* @return String
*/
public String getText(Object arg0) {
// Get the name of the file
String text = ((File) arg0).getName();
// If name is blank, get the path
if (text.length() == 0) {
text = ((File) arg0).getPath();
}
// Check the case settings before returning the text
return preserveCase ? text : text.toUpperCase();
}
/**
* Adds a listener to this label provider
*
* @param arg0
* the listener
*/
public void addListener(ILabelProviderListener arg0) {
listeners.add(arg0);
}
/**
* Called when this LabelProvider is being disposed
*/
public void dispose() {
// Dispose the images
if (dir != null)
dir.dispose();
if (file != null)
file.dispose();
}
/**
* Returns whether changes to the specified property on the specified
* element would affect the label for the element
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty(Object arg0, String arg1) {
return false;
}
/**
* Removes the listener
*
* @param arg0
* the listener to remove
*/
public void removeListener(ILabelProviderListener arg0) {
listeners.remove(arg0);
}
}
Demonstrates TableTree
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class demonstrates TableTree
*/
public class TableTreeTest {
// The number of rows and columns
private static final int NUM = 3;
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("TableTree Test");
createContents(shell);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window"s contents
*
* @param shell the main window
*/
private void createContents(final Shell shell) {
shell.setLayout(new FillLayout());
// Create the TableTree and set some attributes on the underlying table
TableTree tableTree = new TableTree(shell, SWT.NONE);
Table table = tableTree.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(false);
// Create the columns, passing the underlying table
for (int i = 0; i < NUM; i++) {
new TableColumn(table, SWT.LEFT).setText("Column " + (i + 1));
}
// Create the data
for (int i = 0; i < NUM; i++) {
// Create a parent item and add data to the columns
TableTreeItem parent = new TableTreeItem(tableTree, SWT.NONE);
parent.setText(0, "Parent " + (i + 1));
parent.setText(1, "Data");
parent.setText(2, "More data");
// Add children items
for (int j = 0; j < NUM; j++) {
// Create a child item and add data to the columns
TableTreeItem child = new TableTreeItem(parent, SWT.NONE);
child.setText(0, "Child " + (j + 1));
child.setText(1, "Some child data");
child.setText(2, "More child data");
}
// Expand the parent item
parent.setExpanded(true);
}
// Pack the columns
TableColumn[] columns = table.getColumns();
for (int i = 0, n = columns.length; i < n; i++) {
columns[i].pack();
}
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new TableTreeTest().run();
}
}
Demonstrates TreeEditor
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class demonstrates TreeEditor
*/
public class TextTreeEditor {
// Constant for how many items to create at each level
private static final int NUM = 3;
/**
* Runs the //Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Text Tree Editor");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the contents of the main window
*
* @param shell the main window
*/
public void createContents(Shell shell) {
shell.setLayout(new FillLayout());
// Create the tree
final Tree tree = new Tree(shell, SWT.SINGLE);
// Fill the tree with data
for (int i = 0; i < NUM; i++) {
TreeItem iItem = new TreeItem(tree, SWT.NONE);
iItem.setText("Item " + (i + 1));
for (int j = 0; j < NUM; j++) {
TreeItem jItem = new TreeItem(iItem, SWT.NONE);
jItem.setText("Sub Item " + (j + 1));
for (int k = 0; k < NUM; k++) {
new TreeItem(jItem, SWT.NONE).setText("Sub Sub Item " + (k + 1));
}
jItem.setExpanded(true);
}
iItem.setExpanded(true);
}
// Create the editor and set its attributes
final TreeEditor editor = new TreeEditor(tree);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
// Add a key listener to the tree that listens for F2.
// If F2 is pressed, we do the editing
tree.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
// Make sure one and only one item is selected when F2 is pressed
if (event.keyCode == SWT.F2 && tree.getSelectionCount() == 1) {
// Determine the item to edit
final TreeItem item = tree.getSelection()[0];
// Create a text field to do the editing
final Text text = new Text(tree, SWT.NONE);
text.setText(item.getText());
text.selectAll();
text.setFocus();
// If the text field loses focus, set its text into the tree
// and end the editing session
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
item.setText(text.getText());
text.dispose();
}
});
// If they hit Enter, set the text into the tree and end the editing
// session. If they hit Escape, ignore the text and end the editing
// session
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
switch (event.keyCode) {
case SWT.CR:
// Enter hit--set the text into the tree and drop through
item.setText(text.getText());
case SWT.ESC:
// End editing session
text.dispose();
break;
}
}
});
// Set the text field into the editor
editor.setEditor(text, item);
}
}
});
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new TextTreeEditor().run();
}
}
Demonstrates TreeViewer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This class demonstrates TreeViewer. It shows the drives, directories, and
* files on the system.
*/
public class FileTree extends ApplicationWindow {
/**
* FileTree constructor
*/
public FileTree() {
super(null);
}
/**
* Runs the application
*/
public void run() {
// Don"t return from open() until window closes
setBlockOnOpen(true);
// Open the main window
open();
// Dispose the display
Display.getCurrent().dispose();
}
/**
* Configures the shell
*
* @param shell
* the shell
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
// Set the title bar text and the size
shell.setText("File Tree");
shell.setSize(400, 400);
}
/**
* Creates the main window"s contents
*
* @param parent
* the main window
* @return Control
*/
protected Control createContents(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
// Add a checkbox to toggle whether the labels preserve case
Button preserveCase = new Button(composite, SWT.CHECK);
preserveCase.setText("&Preserve case");
// Create the tree viewer to display the file tree
final TreeViewer tv = new TreeViewer(composite);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput("root"); // pass a non-null that will be ignored
// When user checks the checkbox, toggle the preserve case attribute
// of the label provider
preserveCase.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
boolean preserveCase = ((Button) event.widget).getSelection();
FileTreeLabelProvider ftlp = (FileTreeLabelProvider) tv
.getLabelProvider();
ftlp.setPreserveCase(preserveCase);
}
});
return composite;
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new FileTree().run();
}
}
/**
* This class provides the content for the tree in FileTree
*/
class FileTreeContentProvider implements ITreeContentProvider {
/**
* Gets the children of the specified object
*
* @param arg0
* the parent object
* @return Object[]
*/
public Object[] getChildren(Object arg0) {
// Return the files and subdirectories in this directory
return ((File) arg0).listFiles();
}
/**
* Gets the parent of the specified object
*
* @param arg0
* the object
* @return Object
*/
public Object getParent(Object arg0) {
// Return this file"s parent file
return ((File) arg0).getParentFile();
}
/**
* Returns whether the passed object has children
*
* @param arg0
* the parent object
* @return boolean
*/
public boolean hasChildren(Object arg0) {
// Get the children
Object[] obj = getChildren(arg0);
// Return whether the parent has children
return obj == null ? false : obj.length > 0;
}
/**
* Gets the root element(s) of the tree
*
* @param arg0
* the input data
* @return Object[]
*/
public Object[] getElements(Object arg0) {
// These are the root elements of the tree
// We don"t care what arg0 is, because we just want all
// the root nodes in the file system
return File.listRoots();
}
/**
* Disposes any created resources
*/
public void dispose() {
// Nothing to dispose
}
/**
* Called when the input changes
*
* @param arg0
* the viewer
* @param arg1
* the old input
* @param arg2
* the new input
*/
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
// Nothing to change
}
}
/**
* This class provides the labels for the file tree
*/
class FileTreeLabelProvider implements ILabelProvider {
// The listeners
private List listeners;
// Images for tree nodes
private Image file;
private Image dir;
// Label provider state: preserve case of file names/directories
boolean preserveCase;
/**
* Constructs a FileTreeLabelProvider
*/
public FileTreeLabelProvider() {
// Create the list to hold the listeners
listeners = new ArrayList();
// Create the images
try {
file = new Image(null, new FileInputStream("images/file.gif"));
dir = new Image(null, new FileInputStream("images/directory.gif"));
} catch (FileNotFoundException e) {
// Swallow it; we"ll do without images
}
}
/**
* Sets the preserve case attribute
*
* @param preserveCase
* the preserve case attribute
*/
public void setPreserveCase(boolean preserveCase) {
this.preserveCase = preserveCase;
// Since this attribute affects how the labels are computed,
// notify all the listeners of the change.
LabelProviderChangedEvent event = new LabelProviderChangedEvent(this);
for (int i = 0, n = listeners.size(); i < n; i++) {
ILabelProviderListener ilpl = (ILabelProviderListener) listeners
.get(i);
ilpl.labelProviderChanged(event);
}
}
/**
* Gets the image to display for a node in the tree
*
* @param arg0
* the node
* @return Image
*/
public Image getImage(Object arg0) {
// If the node represents a directory, return the directory image.
// Otherwise, return the file image.
return ((File) arg0).isDirectory() ? dir : file;
}
/**
* Gets the text to display for a node in the tree
*
* @param arg0
* the node
* @return String
*/
public String getText(Object arg0) {
// Get the name of the file
String text = ((File) arg0).getName();
// If name is blank, get the path
if (text.length() == 0) {
text = ((File) arg0).getPath();
}
// Check the case settings before returning the text
return preserveCase ? text : text.toUpperCase();
}
/**
* Adds a listener to this label provider
*
* @param arg0
* the listener
*/
public void addListener(ILabelProviderListener arg0) {
listeners.add(arg0);
}
/**
* Called when this LabelProvider is being disposed
*/
public void dispose() {
// Dispose the images
if (dir != null)
dir.dispose();
if (file != null)
file.dispose();
}
/**
* Returns whether changes to the specified property on the specified
* element would affect the label for the element
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty(Object arg0, String arg1) {
return false;
}
/**
* Removes the listener
*
* @param arg0
* the listener to remove
*/
public void removeListener(ILabelProviderListener arg0) {
listeners.remove(arg0);
}
}
Detect a selection or check event in a tree (SWT.CHECK)
/*
* Tree example snippet: detect a selection or check event in a tree (SWT.CHECK)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet114 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Tree tree = new Tree(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
for (int i = 0; i < 12; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("Item " + i);
}
tree.setSize(100, 100);
tree.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
String string = event.detail == SWT.CHECK ? "Checked"
: "Selected";
System.out.println(event.item + " " + string);
}
});
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Detect Mouse Down In SWT Tree Item
/*
* Tree example snippet: detect mouse down in a tree item
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class DetectMouseDownInTreeItem {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
final Tree tree = new Tree(shell, SWT.BORDER | SWT.MULTI);
for (int i = 0; i < 12; i++) {
TreeItem treeItem = new TreeItem(tree, SWT.NONE);
treeItem.setText("Item " + i);
}
tree.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
Point point = new Point(event.x, event.y);
TreeItem item = tree.getItem(point);
if (item != null) {
System.out.println("Mouse down: " + item);
}
}
});
tree.setSize(200, 200);
shell.setSize(300, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Displays a single-selection tree, a multi-selection tree, and a checkbox tree
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* Displays a single-selection tree, a multi-selection tree, and a checkbox tree
*/
public class SWTTreeExample {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("TreeExample");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createContents(Composite composite) {
// Set the single-selection tree in the upper left,
// the multi-selection tree in the upper right,
// and the checkbox tree across the bottom.
// To do this, create a 1x2 grid, and in the top
// cell, a 2x1 grid.
composite.setLayout(new GridLayout(1, true));
Composite top = new Composite(composite, SWT.NONE);
GridData data = new GridData(GridData.FILL_BOTH);
top.setLayoutData(data);
top.setLayout(new GridLayout(2, true));
Tree single = new Tree(top, SWT.SINGLE | SWT.BORDER);
data = new GridData(GridData.FILL_BOTH);
single.setLayoutData(data);
fillTree(single);
Tree multi = new Tree(top, SWT.MULTI | SWT.BORDER);
data = new GridData(GridData.FILL_BOTH);
multi.setLayoutData(data);
fillTree(multi);
Tree check = new Tree(composite, SWT.CHECK | SWT.BORDER);
data = new GridData(GridData.FILL_BOTH);
check.setLayoutData(data);
fillTree(check);
}
/**
* Helper method to fill a tree with data
*
* @param tree the tree to fill
*/
private void fillTree(Tree tree) {
// Turn off drawing to avoid flicker
tree.setRedraw(false);
// Create five root items
for (int i = 0; i < 5; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("Root Item " + i);
// Create three children below the root
for (int j = 0; j < 3; j++) {
TreeItem child = new TreeItem(item, SWT.NONE);
child.setText("Child Item " + i + " - " + j);
// Create three grandchildren under the child
for (int k = 0; k < 3; k++) {
TreeItem grandChild = new TreeItem(child, SWT.NONE);
grandChild.setText("Grandchild Item " + i + " - " + j + " - " + k);
}
}
}
// Turn drawing back on!
tree.setRedraw(true);
}
/**
* The entry point for the application
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new SWTTreeExample().run();
}
}
Insert a SWT tree item (at an index)
/*
* Tree example snippet: insert a tree item (at an index)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet102 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Tree tree = new Tree(shell, SWT.BORDER | SWT.MULTI);
tree.setSize(200, 200);
for (int i = 0; i < 12; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("Item " + i);
}
TreeItem item = new TreeItem(tree, SWT.NONE, 1);
TreeItem[] items = tree.getItems();
int index = 0;
while (index < items.length && items[index] != item)
index++;
item.setText("*** New Item " + index + " ***");
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Limit selection to items that match a pattern in SWT Tree
/*
* Tree example snippet: limit selection to items that match a pattern
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet80 {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Tree tree = new Tree(shell, SWT.BORDER | SWT.MULTI);
for (int i = 0; i < 2; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("item " + i);
for (int j = 0; j < 2; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText("item " + j);
for (int k = 0; k < 2; k++) {
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText("item " + k);
}
}
}
tree.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TreeItem[] selection = tree.getSelection();
TreeItem[] revisedSelection = new TreeItem[0];
for (int i = 0; i < selection.length; i++) {
String text = selection[i].getText();
if (text.indexOf("1") > 0) {
TreeItem[] newSelection = new TreeItem[revisedSelection.length + 1];
System.arraycopy(revisedSelection, 0, newSelection, 0,
revisedSelection.length);
newSelection[revisedSelection.length] = selection[i];
revisedSelection = newSelection;
}
}
tree.setSelection(revisedSelection);
}
});
shell.setSize(300, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Print selected items in a SWT tree
/*
* Tree example snippet: print selected items in a tree
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet61 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
final Tree tree = new Tree(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
for (int i = 0; i < 4; i++) {
TreeItem item0 = new TreeItem(tree, 0);
item0.setText("Item " + i);
for (int j = 0; j < 4; j++) {
TreeItem item1 = new TreeItem(item0, 0);
item1.setText("SubItem " + i + " " + j);
for (int k = 0; k < 4; k++) {
TreeItem item2 = new TreeItem(item1, 0);
item2.setText("SubItem " + i + " " + j + " " + k);
}
}
}
tree.setBounds(0, 0, 100, 100);
tree.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String string = "";
TreeItem[] selection = tree.getSelection();
for (int i = 0; i < selection.length; i++)
string += selection[i] + " ";
System.out.println("Selection={" + string + "}");
}
});
tree.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
String string = "";
TreeItem[] selection = tree.getSelection();
for (int i = 0; i < selection.length; i++)
string += selection[i] + " ";
System.out.println("DefaultSelection={" + string + "}");
}
});
tree.addListener(SWT.Expand, new Listener() {
public void handleEvent(Event e) {
System.out.println("Expand={" + e.item + "}");
}
});
tree.addListener(SWT.Collapse, new Listener() {
public void handleEvent(Event e) {
System.out.println("Collapse={" + e.item + "}");
}
});
tree.getItems()[0].setExpanded(true);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Simple Tree
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on Mar 10, 2004 8:08:56 PM by JACK
* $Id$
*
*****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class SWTSimpleTree {
Display display = new Display();
Shell shell = new Shell(display);
Tree tree;
public SWTSimpleTree() {
shell.setLayout(new GridLayout());
tree = new Tree(shell, SWT.BORDER);
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
TreeItem item = new TreeItem(tree, SWT.NULL);
item.setText("ITEM");
TreeItem item2 = new TreeItem(item, SWT.NULL);
item2.setText("ITEM2");
TreeItem item3 = new TreeItem(item2, SWT.NULL);
item3.setText("ITEM3");
System.out.println("item: " + item.getParent() + ", " + item.getParentItem());
System.out.println("item2: " + item2.getParent() + ", " + item2.getParentItem());
System.out.println(tree.getItemCount());
System.out.println(tree.getItems().length);
shell.setSize(300, 200);
shell.open();
//textUser.forceFocus();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
private void init() {
}
public static void main(String[] args) {
new SWTSimpleTree();
}
}
SWT Tree
/*
* Created on Nov 20, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* @author Steven Holzner
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class SWTTrees {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Trees");
final Tree tree = new Tree(shell, SWT.BORDER);
tree.setSize(290, 290);
shell.setSize(300, 300);
for (int loopIndex1 = 0; loopIndex1 < 5; loopIndex1++) {
TreeItem item0 = new TreeItem(tree, 0);
item0.setText("Level 0 Item " + loopIndex1);
for (int loopIndex2 = 0; loopIndex2 < 5; loopIndex2++) {
TreeItem item1 = new TreeItem(item0, 0);
item1.setText("Level 1 Item " + loopIndex2);
for (int loopIndex3 = 0; loopIndex3 < 5; loopIndex3++) {
TreeItem item2 = new TreeItem(item1, 0);
item2.setText("Level 2 Item " + loopIndex3);
}
}
}
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
SWT Tree Composite
/*
SWT/JFace in Action
GUI Design with Eclipse 3.0
Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic
ISBN: 1932394273
Publisher: Manning
*/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.ruposite;
public class Ch8TreeComposite extends Composite {
public Ch8TreeComposite(Composite parent) {
super(parent, SWT.NULL);
populateControl();
}
protected void populateControl() {
FillLayout compositeLayout = new FillLayout();
setLayout(compositeLayout);
int[] selectionStyle = { SWT.SINGLE, SWT.MULTI };
int[] checkStyle = { SWT.NONE, SWT.CHECK };
for (int selection = 0; selection < selectionStyle.length; selection++) {
for (int check = 0; check < checkStyle.length; check++) {
int style = selectionStyle[selection] | checkStyle[check];
createTreeViewer(style);
}
}
}
private void createTreeViewer(int style) {
TreeViewer viewer = new TreeViewer(this, style);
viewer.setContentProvider(new ITreeContentProvider() {
public Object[] getChildren(Object parentElement) {
return ((TreeNode) parentElement).getChildren().toArray();
}
public Object getParent(Object element) {
return ((TreeNode) element).getParent();
}
public boolean hasChildren(Object element) {
return ((TreeNode) element).getChildren().size() > 0;
}
public Object[] getElements(Object inputElement) {
return ((TreeNode) inputElement).getChildren().toArray();
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
});
viewer.setInput(getRootNode());
}
private TreeNode getRootNode() {
TreeNode root = new TreeNode("root");
root.addChild(new TreeNode("child 1").addChild(new TreeNode(
"subchild 1")));
root.addChild(new TreeNode("child 2").addChild(new TreeNode(
"subchild 2").addChild(new TreeNode("grandchild 1"))));
return root;
}
}
class TreeNode {
private String name;
private List children = new ArrayList();
private TreeNode parent;
public TreeNode(String n) {
name = n;
}
protected Object getParent() {
return parent;
}
public TreeNode addChild(TreeNode child) {
children.add(child);
child.parent = this;
return this;
}
public List getChildren() {
return children;
}
public String toString() {
return name;
}
}
SWT Tree Simple Demo
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class TreeClass {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Tree Example");
final Text text = new Text(shell, SWT.BORDER);
text.setBounds(0, 270, 290, 25);
final Tree tree = new Tree(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
tree.setSize(290, 260);
shell.setSize(300, 330);
for (int loopIndex0 = 0; loopIndex0 < 10; loopIndex0++) {
TreeItem treeItem0 = new TreeItem(tree, 0);
treeItem0.setText("Level 0 Item " + loopIndex0);
for (int loopIndex1 = 0; loopIndex1 < 10; loopIndex1++) {
TreeItem treeItem1 = new TreeItem(treeItem0, 0);
treeItem1.setText("Level 1 Item " + loopIndex1);
for (int loopIndex2 = 0; loopIndex2 < 10; loopIndex2++) {
TreeItem treeItem2 = new TreeItem(treeItem1, 0);
treeItem2.setText("Level 2 Item " + loopIndex2);
}
}
}
tree.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (event.detail == SWT.CHECK) {
text.setText(event.item + " was checked.");
} else {
text.setText(event.item + " was selected");
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
SWT Tree With Multi columns
/*
* Create a Tree with columns
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
public class CreateTreeWithcolumns {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Tree tree = new Tree(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
tree.setHeaderVisible(true);
TreeColumn column1 = new TreeColumn(tree, SWT.LEFT);
column1.setText("Column 1");
column1.setWidth(200);
TreeColumn column2 = new TreeColumn(tree, SWT.CENTER);
column2.setText("Column 2");
column2.setWidth(200);
TreeColumn column3 = new TreeColumn(tree, SWT.RIGHT);
column3.setText("Column 3");
column3.setWidth(200);
for (int i = 0; i < 4; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(new String[] { "item " + i, "abc", "defghi" });
for (int j = 0; j < 4; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem
.setText(new String[] { "subitem " + j, "jklmnop",
"qrs" });
for (int k = 0; k < 4; k++) {
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText(new String[] { "subsubitem " + k, "tuv",
"wxyz" });
}
}
}
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Tree Example
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
public class TreeShellExample {
Display d;
Shell s;
TreeShellExample() {
d = new Display();
s = new Shell(d);
s.setSize(250,200);
s.setText("A Table Shell Example");
s.setLayout(new FillLayout());
Tree t = new Tree(s, SWT.SINGLE | SWT.BORDER);
TreeItem child1 = new TreeItem(t, SWT.NONE, 0);
child1.setText("1");
TreeItem child2 = new TreeItem(t, SWT.NONE, 1);
child2.setText("2");
TreeItem child2a = new TreeItem(child2, SWT.NONE, 0);
child2a.setText("2A");
TreeItem child2b = new TreeItem(child2, SWT.NONE, 1);
child2b.setText("2B");
TreeItem child3 = new TreeItem(t, SWT.NONE, 2);
child3.setText("3");
s.open();
while(!s.isDisposed()){
if(!d.readAndDispatch())
d.sleep();
}
d.dispose();
}
public static void main(String[] argv){
new TreeShellExample();
}
}
Tree Example 2
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class TreeShellExample2 {
Display d;
Shell s;
TreeShellExample2() {
d = new Display();
s = new Shell(d);
s.setSize(250, 200);
s.setText("A Tree Shell Example");
s.setLayout(new FillLayout(SWT.HORIZONTAL));
final Tree t = new Tree(s, SWT.SINGLE | SWT.BORDER);
final TreeItem child1 = new TreeItem(t, SWT.NONE, 0);
child1.setText("1");
child1.setImage(new Image(d, "c:\\icons\\folder.gif"));
final TreeItem child2 = new TreeItem(t, SWT.NONE, 1);
child2.setText("2");
child2.setImage(new Image(d, "c:\\icons\\folder.gif"));
final TreeItem child2a = new TreeItem(child2, SWT.NONE, 0);
child2a.setText("2A");
final TreeItem child2b = new TreeItem(child2, SWT.NONE, 1);
child2b.setText("2B");
final TreeItem child3 = new TreeItem(t, SWT.NONE, 2);
child3.setText("3");
child3.setImage(new Image(d, "c:\\icons\\folder.gif"));
final List l = new List(s, SWT.BORDER | SWT.SINGLE);
t.addTreeListener(new TreeListener() {
public void treeExpanded(TreeEvent e) {
TreeItem ti = (TreeItem) e.item;
ti.setImage(new Image(d, "c:\\icons\\open.gif"));
}
public void treeCollapsed(TreeEvent e) {
TreeItem ti = (TreeItem) e.item;
ti.setImage(new Image(d, "c:\\icons\\folder.gif"));
}
});
t.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TreeItem ti = (TreeItem) e.item;
populateList(ti.getText());
}
private void populateList(String type) {
if (type.equals("1")) {
l.removeAll();
l.add("File 1");
l.add("File 2");
}
if (type.equals("2")) {
l.removeAll();
}
if (type.equals("2A")) {
l.removeAll();
l.add("File 3");
l.add("File 4");
}
if (type.equals("2B")) {
l.removeAll();
l.add("File 5");
l.add("File 6");
}
if (type.equals("3")) {
l.removeAll();
l.add("File 7");
l.add("File 8");
}
}
});
s.open();
while (!s.isDisposed()) {
if (!d.readAndDispatch())
d.sleep();
}
d.dispose();
}
public static void main(String[] argv) {
new TreeShellExample2();
}
}