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 java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
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;
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><A HREF";
    private static Pattern folderPattern = Pattern.compile("\"(\\d+)\">(.*)<");
    private static Pattern urlPattern = Pattern.compile("\"(.*)\".*\"(.*)\".*\"(.*)\".*\"(.*)\">(.*)<");
    private static String KEY_ADD_DATE = "ADD_DATE";
    //private static String KEY_HREF = "HREF";
    //private static String KEY_LAST_VISITED = "LAST_VISITED";
    //private static String KEY_LAST_MODIFIED = "LAST_MODIFIED";
    Display display = new Display();
    Shell shell = new Shell(display);
    Tree tree;
    Label label;
    TreeItem rootItem;
    Image iconRoot = new Image(display, "C:/icons/icon.gif");
    Image iconFolder = new Image(display, "C:/icons/folder.gif");
    Image iconURL = new Image(display, "C:/icons/file.gif");
    TreeItem dragSourceItem;
    public BookmarkOrganizer() {

shell.setText("Bookmark organizer");
        shell.setLayout(new GridLayout(1, true));
        ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
        ToolItem itemOpen = new ToolItem(toolBar, SWT.PUSH);
        itemOpen.setText("Load");
        itemOpen.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                FileDialog dialog = new FileDialog(shell, SWT.OPEN);
                String file = dialog.open();
                if (file != null) {
                    TreeItem[] items = rootItem.getItems();
                    for (int i = 0; i < items.length; i++)
                        items[i].dispose();
                    loadBookmark(new File(file), rootItem);
                    setStatus("Bookmarks loaded successfully");
                }
            }
        });
        ToolItem itemSave = new ToolItem(toolBar, SWT.PUSH);
        itemSave.setText("Save as");
        itemSave.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                FileDialog dialog = new FileDialog(shell, SWT.SAVE);
                String file = dialog.open();
                if (file != null) {
                    try {
                        BufferedWriter writer =
                            new BufferedWriter(new FileWriter(file));
                        saveBookmark(writer, rootItem);
                        writer.close();
                        setStatus(
                            "Bookmarks saved successfully to file: " + file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        tree = new Tree(shell, SWT.BORDER);
        tree.setLayoutData(new GridData(GridData.FILL_BOTH));
        rootItem = new TreeItem(tree, SWT.NULL);
        rootItem.setText("BOOKMARKS");
        rootItem.setImage(iconRoot);
        label = new Label(shell, SWT.BORDER);
        label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        final DragSource dragSource =
            new DragSource(tree, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
        dragSource.setTransfer(
            new Transfer[] { BookmarkTransfer.getInstance()});
        dragSource.addDragListener(new DragSourceAdapter() {
            public void dragStart(DragSourceEvent event) {
                TreeItem[] selection = tree.getSelection();
                if (selection.length > 0 && selection[0].getData() != null) {
                    event.doit = true;
                    dragSourceItem = selection[0];
                } else {
                    event.doit = false;
                }
            };
            public void dragSetData(DragSourceEvent event) {
                if (BookmarkTransfer
                    .getInstance()
                    .isSupportedType(event.dataType))
                    event.data = dragSourceItem.getData();
            }
            public void dragFinished(DragSourceEvent event) {
                if (event.detail == DND.DROP_MOVE)
                    dragSourceItem.dispose();
                dragSourceItem = null;
            }
        });
        final DropTarget dropTarget =
            new DropTarget(tree, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
        dropTarget.setTransfer(
            new Transfer[] { BookmarkTransfer.getInstance()});
        dropTarget.addDropListener(new DropTargetAdapter() {
            public void dragOver(DropTargetEvent event) {
                event.feedback =
                    DND.FEEDBACK_EXPAND
                        | DND.FEEDBACK_SCROLL
                        | DND.FEEDBACK_SELECT;
            }
            public void dropAccept(DropTargetEvent event) {
                if (event.item == null
                    || ((TreeItem) event.item).getData() != null)
                    event.detail = DND.DROP_NONE;
            }
            public void drop(DropTargetEvent event) {
                try {
                    if (event.data == null) {
                        event.detail = DND.DROP_NONE;
                        return;
                    }
                    TreeItem item = new TreeItem((TreeItem) event.item, SWT.NULL);
                    Bookmark bookmark = (Bookmark) event.data;
                    item.setText(bookmark.name);
                    item.setImage(iconURL);
                    item.setData(bookmark);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }
            }
        });
        tree.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                TreeItem item = (TreeItem) e.item;
                Bookmark bookmark = (Bookmark) item.getData();
                if (bookmark != null) {
                    setStatus(bookmark.href);
                } else if (item.getData(KEY_ADD_DATE) != null) {
                    setStatus("Folder: " + item.getText());
                }
            }
        });
        shell.setSize(400, 300);
        shell.open();
        loadBookmark(new File("C:/icons/mybookmark.htm"), rootItem);
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }
    private void saveBookmark(BufferedWriter writer, TreeItem item)
        throws IOException {
        if (item.getData() == null
            && item.getData(KEY_ADD_DATE) == null) {
            writer.write(
                "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n"
                    + "<!-- This is an automatically generated file.\n"
                    + "It will be read and overwritten.\n"
                    + "Do Not Edit! -->\n"
                    + "<TITLE>Bookmarks</TITLE>\n"
                    + "<H1>Bookmarks</H1>\n"
                    + "<DL><p>\n");
            TreeItem[] items = item.getItems();
            for (int i = 0; i < items.length; i++)
                saveBookmark(writer, items[i]);
            writer.write("</DL><p>\n");
        } else if (item.getData() == null) {
            writer.write(
                "\t<DT><H3 FOLDED ADD_DATE=\""
                    + item.getData(KEY_ADD_DATE)
                    + "\">"
                    + item.getText()
                    + "</H3>\n");
            writer.write("\t<DL><p>\n");
            TreeItem[] items = item.getItems();
            for (int i = 0; i < items.length; i++)
                saveBookmark(writer, items[i]);
            writer.write("\t</DL><p>\n");
        } else {
            Bookmark bookmark = (Bookmark) item.getData();
            writer.write(
                "\t\t<DT><A HREF="\" HREF="\"""
                    + bookmark.href
                    + "\" ADD_DATE=\""
                    + bookmark.addDate
                    + "\" LAST_VISIT=\""
                    + bookmark.lastVisited
                    + "\" LAST_MODIFIED=\" +"
                    + bookmark.lastModified
                    + "\">"
                    + bookmark.name
                    + "</A>\n");
        }
    }
    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)) {
                    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)) {
                    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();
    }
}

BookmarkTransfer.java


代码如下:

package swt_jface.demo11;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;
public 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;
    }
    protected int[] getTypeIds() {
        return new int[] { BOOKMARK_TRANSFER_ID };
    }
    protected String[] getTypeNames() {
        return new String[] { BOOKMARK_TRANSFER_NAME };
    }
    protected void javaToNative(Object object, TransferData transferData) {
        if (object == null || !(object instanceof Bookmark)) return;
        Bookmark bookmark = (Bookmark) object;
        if (isSupportedType(transferData)) {
            try {
                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();
            }
        }
    }
    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;
        }
    }
}

mybookmark.htm

(0)

相关推荐

  • 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

  • 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)小制作 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)小制作 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)体验之GridLayout布局

    GridLayout布局 GridLayout 布局的功能非常强大,也是笔者常用的一种布局方式.GridLayout是网格式布局,它把父组件分成一个表格,默认情况下每个子组件占据一个单元格的空间,每个子组件按添加到父组件的顺序排列在表格中.GridLayout提供了很多的属性,可以灵活设置网格的信息.另外,GridLayout 布局提供了GridData类,子组件可以设置相应的GridData,例如 "dogPhoto.setLayoutData(gridData)",GridData

  • SWT(JFace) 简易浏览器 制作实现代码第1/2页

    代码如下: BrowserExample.java 复制代码 代码如下: package swt_jface.demo5; import java.text.MessageFormat; import java.util.MissingResourceException; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.browser.Browser; import org.e

  • SWT(JFace) FTP客户端实现

    Jar包一览: org.eclipse.jface_3.4.2.M20090107-0800.jar org.eclipse.swt.win32.win32.x86_3.4.1.v3452b.jar org.eclipse.core.commands_3.4.0.I20080509-2000.jar org.eclipse.core.runtime_3.4.0.v20080512.jar org.eclipse.equinox.common_3.4.0.v20080421-2006.jar or

  • SWT(JFace) Wizard(Eclipse插件编程必备)

    演示代码如下: HotelReservation.java 复制代码 代码如下: package swt_jface.demo12; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclips

  • SWT(JFace) 打印功能

    演示代码如下: 复制代码 代码如下: package swt_jface.demo11; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.printing.PrintDialog; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.printing.PrinterData; import org.eclipse.swt.widgets.Display

  • SWT(JFace) 文本编辑器 实现代码

    代码如下: 实现1: BasicEditor.java 复制代码 代码如下: package swt_jface.demo5; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.eclipse.jface.resource.ImageDescriptor; i

随机推荐