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();
}
}

(0)

相关推荐

  • 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 o

  • SWT JFace 小制作 文本阅读器

    代码如下: 复制代码 代码如下: package swt_jface.demo11; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonit

  • SWT(JFace)小制作 BugTracker

    代码如下: 实现1: BugTracker.java 复制代码 代码如下: package swt_jface.demo6; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import j

  • SWT JFace Bookmark 制作

    代码如下: BookmarkOrganizer.java 复制代码 代码如下: package swt_jface.demo11; 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 ja

  • 基于Python制作一个文件去重小工具

    目录 前言 实现步骤 补充 前言 常常在下载网络素材时有很多的重复文件乱七八糟的,于是想实现一个去重的操作. 主要实现思路就是遍历出某个文件夹包括其子文件夹下面的所有文件,最后,将所有文件通过MD5函数的对比筛选出来,最后将重复的文件移除. 实现步骤 用到的第三方库都比较的常见,其中只有hashlib是用来对比文件的不是很常见.其他的都是一些比较常见的第三方库用来做辅助操作. import os # 应用文件操作 import hashlib # 文件对比操作 import logging #

  • 基于PyQt5制作Excel文件数据去重小工具

    需求说明:将单个或者多个Excel文件数据进行去重操作,去重的列可以通过自定义制定. 开始源码说明之前,先说明一下工具的使用过程. 1.准备需要去重的数据文件. 2.使用工具执行去重操作. 3.处理完成后的结果文件. PyQt5 界面UI相关的模块引用 from PyQt5.QtWidgets import * from PyQt5.QtGui import * 核心组件 from PyQt5.QtCore import * 主题样式模块引用 from QCandyUi import Candy

  • 基于Python制作一个文件解压缩工具

    经常由于各种压缩格式的不一样用到文件的解压缩时就需要下载不同的解压缩工具去处理不同的文件,以至于桌面上的压缩工具就有三四种,于是使用python做了一个包含各种常见格式的文件解压缩的小工具. 常见的压缩格式主要是下面的四种格式: zip 格式的压缩文件,一般使用360压缩软件进行解压缩. tar.gz 格式的压缩文件,一般是在linux系统上面使用tar命令进行解压缩. rar 格式的压缩文件,一般使用rar压缩软件进行解压缩. 7z 格式的压缩文件,一般使用7-zip压缩软件进行解压缩. 导入

  • 将python包发布到PyPI和制作whl文件方式

    wheel文件 Wheel和Egg都是python的打包格式,目的是支持不需要编译或制作的安装过程,实际上也是一种压缩文件,将.whl的后缀改为.zip即可可看到压缩包里面的内容.按照官网说法,wheels是发行版Python的新标准并且要取代.egg. Egg格式是由setuptools在2004年引入,而Wheel格式是由PEP427在2012年定义. Wheel现在被认为是Python的二进制包的标准格式. 以下是Wheel和Egg的主要的不同点: Wheel有一个官方的PEP427来定义

  • python基于pyppeteer制作PDF文件

    Pyppeteer 是什么 介绍 Pyppeteer 之前,有必要先介绍一下 Puppeteer,Puppeteer 是谷歌官方出的一个通过DevTools协议控制headless Chrome的Node库.通过Puppeteer可以直接控制Chrome浏览器模拟大部分用户操作. 所谓Headless Chrome 就是 Chrome 浏览器的无界面形态. 而 Pyppeteer 就是 Puppeteer 的 Python 版本非官方实现,它是一位来自于日本的工程师依据 Puppeteer 的一

  • 用Python制作一个文件加密器

    目录 前言 下载地址 效果预览 加密算法 总结 前言 因为一些懂得都懂的原因,我的父母对于我电脑上的文件内容特别感兴趣.为了防止信息泄露,我连夜用Python做了一个文件加密器,防止我的重要信息被泄露. 下载地址 github:https://github.com/13337356453/FileCipher GitHub上的资源是Python源代码 效果预览 为了方便操作,我用PyQt做了窗口.运行起来是这样的. 加密效果还是很不错了 加密算法 对于我来说,程序中gui的编写算比较简单.困难的

随机推荐