程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> SWT(JFace)小制造 FileBrowser文件閱讀

SWT(JFace)小制造 FileBrowser文件閱讀

編輯:關於JAVA

SWT(JFace)小制造 FileBrowser文件閱讀。本站提示廣大學習愛好者:(SWT(JFace)小制造 FileBrowser文件閱讀)文章只能為提供參考,不一定能成為您想要的結果。以下是SWT(JFace)小制造 FileBrowser文件閱讀正文


代碼如下:

package swt_jface.demo6;
import java.io.File;
import java.util.Date;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class FileBrowser {

Display display = new Display();
Shell shell = new Shell(display);
Table table;
File rootDir;
Image iconFolder = new Image(shell.getDisplay(), "C:/icons/folder.gif");
Image iconFile = new Image(shell.getDisplay(), "C:/icons/file.gif");

public FileBrowser() {

GridLayout gridLayout = new GridLayout();
shell.setLayout(gridLayout);
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
//table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumn tcFileName = new TableColumn(table, SWT.LEFT);
tcFileName.setText("File name");
//tcFileName.setImage(new Image(shell.getDisplay(), "icons/folder.gif"));
TableColumn tcFileSize = new TableColumn(table, SWT.RIGHT);
tcFileSize.setText("Size");

TableColumn tcDateModified = new TableColumn(table, SWT.RIGHT);
tcDateModified.setText("Date Modified");
tcFileName.setWidth(200);
tcFileSize.setWidth(80);
tcDateModified.setWidth(180);
TableItem item = new TableItem(table, SWT.NULL);
item.setText(new String[]{"Name", "Size"});
table.setLayoutData(new GridData(GridData.FILL_BOTH));
table.pack();

shell.pack();
shell.open();
setRootDirectory(new File("."));

while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}

private void setRootDirectory(File dir) {
this.rootDir = dir;
if(! (dir.exists() && dir.isDirectory()))
throw new IllegalArgumentException("Invalid directory. ");
table.removeAll();
File[] files = dir.listFiles();
for(int i=0; files != null && i < files.length; i++) {
File file = files[i];
TableItem item = new TableItem(table, SWT.NULL);
item.setBackground(i % 2 == 0 ? shell.getDisplay().getSystemColor(SWT.COLOR_WHITE) :
shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
item.setText(0, file.getName());
item.setText(2, new Date(file.lastModified()).toString());
if(file.isDirectory()) {
item.setImage(0, iconFolder);
}else{
int lastDot = file.getName().lastIndexOf('.');
if(lastDot >= 0 && lastDot < file.getName().length()) {
item.setImage(0, getIcon(file.getName().substring(lastDot+1)));
}
long kbytes = file.length() / 1024;
if(kbytes == 0)
kbytes = 1;
item.setText(1, kbytes + " KB");
}
}
}

private ImageRegistry imageRegistry;

public Image getIcon(String extension) {
if(imageRegistry == null)
imageRegistry = new ImageRegistry();
Image image = imageRegistry.get(extension);
if(image != null)
return image;
Program program = Program.findProgram(extension);
if(program != null) {
image = new Image(shell.getDisplay(), program.getImageData());
imageRegistry.put(extension, image);
}else{
image = iconFile;
}
return image;
}
public static void main(String[] args) {
new FileBrowser();
}
}

更多的Table操作的例子:

package swt_jface.demo6;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
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.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
public class Main {

public static void main(String[] args) {

Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
table.setLinesVisible(true);
for (int i = 0; i < 3; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setWidth(100);
}
for (int i = 0; i < 3; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "" + i, "" + i, "" + i });
}
final TableEditor editor = new TableEditor(table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
table.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
Rectangle clientArea = table.getClientArea();
Point pt = new Point(event.x, event.y);
int index = table.getTopIndex();
while (index < table.getItemCount()) {
boolean visible = false;
final TableItem item = table.getItem(index);
for (int i = 0; i < table.getColumnCount(); i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
final int column = i;
final Text text = new Text(table, SWT.NONE);
Listener textListener = new Listener() {
public void handleEvent(final Event e) {
switch (e.type) {
case SWT.FocusOut:
item.setText(column, text.getText());
text.dispose();
break;
case SWT.Traverse:
switch (e.detail) {
case SWT.TRAVERSE_RETURN:
item.setText(column, text.getText());
case SWT.TRAVERSE_ESCAPE:
text.dispose();
e.doit = false;
}
break;
}
}
};
text.addListener(SWT.FocusOut, textListener);
text.addListener(SWT.Traverse, textListener);
editor.setEditor(text, item, i);
text.setText(item.getText(i));
text.selectAll();
text.setFocus();
return;
}
if (!visible && rect.intersects(clientArea)) {
visible = true;
}
}
if (!visible)
return;
index++;
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

上面的代碼是對FileBrowser功用的加強:
完成1:
FileBrowser.java

package swt_jface.demo7;
import java.io.File;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.DirectoryDialog;
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.ToolBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class FileBrowser {

Display display = new Display();
Shell shell = new Shell(display);
Tree tree;
File rootDir;
public FileBrowser() {

Action actionSetRootDir = new Action("Set Root Dir") {
public void run() {
DirectoryDialog dialog = new DirectoryDialog(shell);
String path = dialog.open();
if (path != null) {
setRootDir(new File(path));
}
}
};
ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
ToolBarManager manager = new ToolBarManager(toolBar);
manager.add(actionSetRootDir);
manager.update(true);
shell.setLayout(new GridLayout());
tree = new Tree(shell, SWT.BORDER);
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
setRootDir(new File("C:/temp"));
tree.addTreeListener(new TreeListener() {
public void treeCollapsed(TreeEvent e) {
}
public void treeExpanded(TreeEvent e) {
TreeItem item = (TreeItem) e.item;
TreeItem[] children = item.getItems();
for (int i = 0; i < children.length; i++)
if (children[i].getData() == null)
children[i].dispose();
else
return;
File[] files = ((File) item.getData()).listFiles();
for (int i = 0; files != null && i < files.length; i++)
addFileToTree(item, files[i]);
}
});
tree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
}
public void widgetDefaultSelected(SelectionEvent e) {
TreeItem item = (TreeItem) e.item;
File file = (File) item.getData();
if (Program.launch(file.getAbsolutePath())) {
System.out.println("File has been launched: " + file);
} else {
System.out.println("Unable to launch file: " + file);
}
}
});
final TreeEditor editor = new TreeEditor(tree);
tree.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
Point point = new Point(event.x, event.y);
final TreeItem item = tree.getItem(point);
if (item == null)
return;
final Text text = new Text(tree, SWT.NONE);
text.setText(item.getText());
text.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_YELLOW));
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
editor.setEditor(text, item);
Listener textListener = new Listener() {
public void handleEvent(final Event e) {
switch (e.type) {
case SWT.FocusOut :
File renamed =
renameFile(
(File) item.getData(),
text.getText());
if (renamed != null) {
item.setText(text.getText());
item.setData(renamed);
}
text.dispose();
break;
case SWT.Traverse :
switch (e.detail) {
case SWT.TRAVERSE_RETURN :
renamed =
renameFile(
(File) item.getData(),
text.getText());
if (renamed != null) {
item.setText(text.getText());
item.setData(renamed);
}
case SWT.TRAVERSE_ESCAPE :
text.dispose();
e.doit = false;
}
break;
}
}
};
text.addListener(SWT.FocusOut, textListener);
text.addListener(SWT.Traverse, textListener);
text.setFocus();
}
});

shell.setSize(400, 260);
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private File renameFile(File file, String newName) {
File dest = new File(file.getParentFile(), newName);
if (file.renameTo(dest)) {
return dest;
} else {
return null;
}
}
private void setRootDir(File root) {
if( (!root.isDirectory()) || (!root.exists()))
throw new IllegalArgumentException("Invalid root: " + root);
this.rootDir = root;
shell.setText("Now browsing: " + root.getAbsolutePath());
if (tree.getItemCount() > 0) {
TreeItem[] items = tree.getItems();
for (int i = 0; i < items.length; i++) {
items[i].dispose();
}
}
File[] files = root.listFiles();
for(int i=0; files != null && i < files.length; i++)
addFileToTree(tree, files[i]);
}
private void addFileToTree(Object parent, File file) {
TreeItem item = null;
if (parent instanceof Tree)
item = new TreeItem((Tree) parent, SWT.NULL);
else if (parent instanceof TreeItem)
item = new TreeItem((TreeItem) parent, SWT.NULL);
else
throw new IllegalArgumentException(
"parent should be a tree or a tree item: " + parent);
item.setText(file.getName());
item.setImage(getIcon(file));
item.setData(file);
if (file.isDirectory()) {
// // recursively adds all the children of this file.
// File[] files = file.listFiles();
// for(int i=0; i<files.length; i++)
// buildTree(item, files[i]);
if (file.list() != null && file.list().length > 0)
new TreeItem(item, SWT.NULL);
}
}
private ImageRegistry imageRegistry;
Image iconFolder = new Image(shell.getDisplay(), "C:/icons/folder.gif");
Image iconFile = new Image(shell.getDisplay(), "C:/icons/file.gif");
private Image getIcon(File file) {
if (file.isDirectory())
return iconFolder;
int lastDotPos = file.getName().indexOf('.');
if (lastDotPos == -1)
return iconFile;
Image image = getIcon(file.getName().substring(lastDotPos + 1));
return image == null ? iconFile : image;
}
private Image getIcon(String extension) {
if (imageRegistry == null)
imageRegistry = new ImageRegistry();
Image image = imageRegistry.get(extension);
if (image != null)
return image;
Program program = Program.findProgram(extension);
ImageData imageData = (program == null ? null : program.getImageData());
if (imageData != null) {
image = new Image(shell.getDisplay(), imageData);
imageRegistry.put(extension, image);
} else {
image = iconFile;
}
return image;
}
public static void main(String[] args) {
new FileBrowser();
}
}

完成2:
FileBrowserJFace.java

package swt_jface.demo7;
import java.io.File;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.IStructuredSelection;
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.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
public class FileBrowserJFace {

Display display = new Display();
Shell shell = new Shell(display);

File rootDir;
TreeViewer treeViewer;
public FileBrowserJFace() {
Action actionSetRootDir = new Action("Set Root Dir") {
public void run() {
DirectoryDialog dialog = new DirectoryDialog(shell);
String path = dialog.open();
if (path != null) {
treeViewer.setInput(new File(path));
}
}
};
final ViewerFilter directoryFilter = new ViewerFilter() {
public boolean select(
Viewer viewer,
Object parentElement,
Object element) {
return ((File)element).isDirectory();
}
};
Action actionShowDirectoriesOnly = new Action("Show directories only") {
public void run() {
if(! isChecked())
treeViewer.removeFilter(directoryFilter);
else
treeViewer.addFilter(directoryFilter);
}
};
actionShowDirectoriesOnly.setChecked(false);
Action actionDeleteFile = new Action("Delete the selected file") {
public void run() {
IStructuredSelection selection = (IStructuredSelection)treeViewer.getSelection();
File file = (File)selection.getFirstElement();
if(file == null) {
System.out.println("Please select a file first.");
return;
}
MessageBox messageBox = new MessageBox(shell, SWT.YES | SWT.NO);
messageBox.setMessage("Are you sure to delete file: " + file.getName() + "?");
if(messageBox.open() == SWT.YES) {
File parentFile = file.getParentFile();
if(file.delete()) {
System.out.println("File has been deleted. ");
// Notifies the viewer for update.
treeViewer.refresh(parentFile, false);
}else{
System.out.println("Unable to delete file.");
}
}
}
};
ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
ToolBarManager manager = new ToolBarManager(toolBar);
manager.add(actionSetRootDir);
manager.add(actionShowDirectoriesOnly);
manager.add(actionDeleteFile);
manager.update(true);

shell.setLayout(new GridLayout());
treeViewer = new TreeViewer(shell, SWT.BORDER);
treeViewer.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
treeViewer.setContentProvider(new ITreeContentProvider() {
public Object[] getChildren(Object parentElement) {
File[] files = ((File)parentElement).listFiles();
if(files == null)
return new Object[0];
return files;
}
public Object getParent(Object element) {
return ((File)element).getParentFile();
}
public boolean hasChildren(Object element) {
File file = (File)element;
File[] files = file.listFiles();
if(files == null || files.length == 0)
return false;
return true;
}
public Object[] getElements(Object inputElement) {
File[] files = ((File)inputElement).listFiles();
if(files == null)
return new Object[0];
return files;
}
public void dispose() {
}
public void inputChanged(
Viewer viewer,
Object oldInput,
Object newInput) {
shell.setText("Now browsing: " + newInput);
}
});

treeViewer.setLabelProvider(new LabelProvider() {
public Image getImage(Object element) {
return getIcon((File)element);
}
public String getText(Object element) {
return ((File)element).getName();
}
});
treeViewer.setSorter(new ViewerSorter() {
public int category(Object element) {
File file = (File)element;
if(file.isDirectory())
return 0;
else
return 1;
}
});


treeViewer.setInput(new File("C:/temp"));
shell.setSize(400, 260);
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
// private File renameFile(File file, String newName) {
// File dest = new File(file.getParentFile(), newName);
// if (file.renameTo(dest)) {
// return dest;
// } else {
// return null;
// }
// }
private ImageRegistry imageRegistry;
Image iconFolder = new Image(shell.getDisplay(), "C:/icons/folder.gif");
Image iconFile = new Image(shell.getDisplay(), "C:/icons/file.gif");
private Image getIcon(File file) {
if (file.isDirectory())
return iconFolder;
int lastDotPos = file.getName().indexOf('.');
if (lastDotPos == -1)
return iconFile;
Image image = getIcon(file.getName().substring(lastDotPos + 1));
return image == null ? iconFile : image;
}
private Image getIcon(String extension) {
if (imageRegistry == null)
imageRegistry = new ImageRegistry();
Image image = imageRegistry.get(extension);
if (image != null)
return image;
Program program = Program.findProgram(extension);
ImageData imageData = (program == null ? null : program.getImageData());
if (imageData != null) {
image = new Image(shell.getDisplay(), imageData);
imageRegistry.put(extension, image);
} else {
image = iconFile;
}
return image;
}

public static void main(String[] args) {
new FileBrowserJFace();
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved