项目需要,从XML中读取数据生成一个Tree,然后可以对叶子节点的值(属性不可以)进行编辑,并最后保存。
XML文件是我们项目中的文件,就不提供了,随便一个XML都可以拿来测试。
/**
* chega
* 2012-12-17下午2:11:42
*/
package com.java2s.www;
import java.io.File;
import java.io.IOException;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
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.custom.TreeEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class E10FieldTree
{
public static void main(String[] args) throws JDOMException, IOException
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
final E10FieldTree e10 = new E10FieldTree(shell);
Composite btnComp = new Composite(shell, SWT.NONE);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
btnComp.setLayoutData(gridData);
// btnComp.setBackground(display.getSystemColor(SWT.COLOR_RED));
FormLayout layout = new FormLayout();
btnComp.setLayout(layout);
Button btn = new Button(btnComp, SWT.PUSH);
FormData data = new FormData();
data.top = new FormAttachment(0, 0);
data.right = new FormAttachment(100, -40);
data.bottom = new FormAttachment(100);
btn.setText("Save");
btn.setLayoutData(data);
btn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent selectionevent)
{
try
{
e10.saveXML();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
shell.setSize(new Point(600, 500));
shell.setVisible(true);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
public void saveXML() throws IOException
{
XMLOutputter outputter = new XMLOutputter();
Format format = Format.getPrettyFormat();
// jdom在输出到不同的目的地时,中文可能会产生乱码。输出到文件用FileOutputStream而不能用FileWriter,输出到控制台要用PrintWriter而不能直接用System.out(见网上讨论)
// 还可以强制设定输出编码,这样就不用考虑中文编码问题了
format.setEncoding("utf-8");
outputter.output(this.document, System.out);
}
private Shell parent;
private TreeViewer treeViewer;
private Text text;
private TreeEditor editor;
private Document document;
private Document copyDocument;
private boolean isEditing = false;
public E10FieldTree(Shell parent) throws JDOMException, IOException
{
this.parent = parent;
this.init();
}
private void init() throws JDOMException, IOException
{
this.treeViewer = new TreeViewer(this.parent, SWT.SINGLE | SWT.FULL_SELECTION);
GridData data = new GridData(GridData.FILL_BOTH);
this.treeViewer.getTree().setLayoutData(data);
this.treeViewer.getTree().setLinesVisible(true);
this.treeViewer.getTree().setHeaderVisible(true);
this.treeViewer.setAutoExpandLevel(1);
TreeColumn column1 = new TreeColumn(this.treeViewer.getTree(), 0);
column1.setText("Key");
column1.setWidth(150);
TreeColumn column2 = new TreeColumn(this.treeViewer.getTree(), 1);
column2.setText("Value");
column2.setWidth(250);
document = new SAXBuilder().build(new File("Group_ITEM.xml"));
this.copyDocument = (Document) this.document.clone();
this.treeViewer.setContentProvider(new ITreeContentProvider() {
@Override
public void dispose()
{
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
@Override
public Object[] getElements(Object inputElement)
{
if (inputElement == document)
{
return new Element[] { document.getRootElement() };
}
else
{
Element ele = (Element) inputElement;
return ele.getChildren().toArray();
}
}
@Override
public Object[] getChildren(Object parentElement)
{
Element ele = (Element) parentElement;
return ele.getChildren().toArray();
}
@Override
public Object getParent(Object element)
{
Element ele = (Element) element;
return ele.getParentElement();
}
@Override
public boolean hasChildren(Object element)
{
return this.getChildren(element).length > 0;
}
});
this.treeViewer.setLabelProvider(new ITableLabelProvider() {
@Override
public void addListener(ILabelProviderListener listener)
{
}
@Override
public void dispose()
{
}
@Override
public boolean isLabelProperty(Object element, String property)
{
return false;
}
@Override
public void removeListener(ILabelProviderListener listener)
{
}
@Override
public Image getColumnImage(Object element, int columnIndex)
{
return null;
}
@Override
public String getColumnText(Object element, int columnIndex)
{
Element ele = (Element) element;
if (columnIndex == 0)
{
return ele.getName();
}
if (columnIndex == 1)
{
if (!((ITreeContentProvider) treeViewer.getContentProvider()).hasChildren(element))
{
return ele.getValue();
}
}
return null;
}
});
this.treeViewer.setInput(document);
this.treeViewer.expandAll();
editor = new TreeEditor(this.treeViewer.getTree());
editor.grabHorizontal = true;
editor.grabVertical = true;
text = new Text(this.treeViewer.getTree(), SWT.SINGLE | SWT.BORDER);
text.setVisible(false);
final FocusListener focusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent focusevent)
{
beginEdit();
}
@Override
public void focusLost(FocusEvent focusevent)
{
finishEdit();
}
};
text.addFocusListener(focusListener);
text.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent keyevent)
{
// 回车直接确认修改
if (keyevent.character == SWT.CR)
{
finishEdit();
}
// ESC取消修改
if (keyevent.character == SWT.ESC)
{
cancelEdit();
}
}
});
this.treeViewer.getTree().addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e)
{
TreeItem selectedItem = treeViewer.getTree().getItem(new Point(e.x, e.y));
if (selectedItem == null)
{
return;
}
// 只有叶节点才允许修改
if (selectedItem.getItemCount() == 0)
{
if (canEdit(e.x, 1))
{
editor.setEditor(text, selectedItem, 1);
text.setText(selectedItem.getText(1));
text.selectAll();
text.forceFocus();
}
}
}
});
}
/**
* 开始修改
*/
protected void beginEdit()
{
this.isEditing = true;
text.setText(editor.getItem().getText(1));
text.selectAll();
text.setVisible(true);
}
/**
* 提交修改(提交修改的时候同时修改Document对象)
*/
protected void finishEdit()
{
if(!this.isEditing){
return ;
}
System.out.println("finishEdit");
this.isEditing = false;
editor.getItem().setText(1, text.getText().trim());
((Element) editor.getItem().getData()).setText(text.getText().trim());
text.setText("");
text.setVisible(false);
}
/**
* 取消修改
*/
protected void cancelEdit()
{
this.isEditing = false;
text.setText("");
text.setVisible(false);
}
/**
* 判断x坐标是否在第columnIdx列内(起始列索引为0)
*
* @param x
* @param columnIdx
* @return
*/
protected boolean canEdit(int x, int columnIdx)
{
if (columnIdx >= this.treeViewer.getTree().getColumnCount())
{
return false;
}
int leftWidth = 0;
int rightWidth = 0;
for (int i = 0; i < columnIdx; i++)
{
leftWidth += this.treeViewer.getTree().getColumn(i).getWidth();
}
rightWidth = leftWidth + this.treeViewer.getTree().getColumn(columnIdx).getWidth();
return leftWidth <= x && x <= rightWidth;
}
/**
* 取得原始的Document
*
* @return
*/
public Document getOriginalDocument()
{
return this.copyDocument;
}
public Document getDocumentInUse()
{
return this.document;
}
}
XML文件是我们项目中的文件,就不提供了,随便一个XML都可以拿来测试。