微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 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 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 TableColumn column = new TableColumn(table, SWT.NONE);

column.setWidth(100);

}

for (int i = 0; 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 boolean visible = false;

final TableItem item = table.getItem(index);

for (int i = 0; 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 if (children[i].getData() == null)

children[i].dispose();

else

return;

File[] files = ((File) item.getData()).listFiles();

for (int i = 0; files != null && 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[i].dispose();

}

}

File[] files = root.listFiles();

for(int i=0; files != null && 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// 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();

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐