Java/SWT JFace Eclipse/Browser HTML — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:56, 1 июня 2010
Содержание
- 1 Another SWT Browser
- 2 Another SWT Browser Demo
- 3 Bring up a browser
- 4 HTML Explorer
- 5 HTML Explorer based on JFace
- 6 Implements a web browser
- 7 Implements a web browser 2
- 8 Modify HTML title tag
- 9 Query DOM node value
- 10 Render HTML that includes relative links from memory
- 11 SWT Browser
- 12 SWT Browser Example
- 13 Uses a web browser to display
- 14 Web Browser Composite
Another SWT Browser
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
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.ToolItem;
public class BrowserClass {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Browser Example");
shell.setSize(620, 500);
ToolBar toolbar = new ToolBar(shell, SWT.NONE);
toolbar.setBounds(5, 5, 200, 30);
ToolItem goButton = new ToolItem(toolbar, SWT.PUSH);
goButton.setText("Go");
ToolItem backButton = new ToolItem(toolbar, SWT.PUSH);
backButton.setText("Back");
ToolItem stopButton = new ToolItem(toolbar, SWT.PUSH);
stopButton.setText("Stop");
final Text text = new Text(shell, SWT.BORDER);
text.setBounds(5, 35, 400, 25);
final Browser browser = new Browser(shell, SWT.NONE);
browser.setBounds(5, 75, 600, 400);
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem) event.widget;
String string = item.getText();
if (string.equals("Back"))
browser.back();
else if (string.equals("Stop"))
browser.stop();
else if (string.equals("Go"))
browser.setUrl(text.getText());
}
};
goButton.addListener(SWT.Selection, listener);
backButton.addListener(SWT.Selection, listener);
stopButton.addListener(SWT.Selection, listener);
text.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(text.getText());
}
});
shell.open();
browser.setUrl("http://oreilly.ru");
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Another SWT Browser Demo
import java.io.IOException;
import java.io.InputStream;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.CloseWindowListener;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class SWTBrowserDemo {
int index;
boolean busy;
Image images[];
Image icon = null;
boolean title = false;
Composite parent;
Text locationBar;
Browser browser;
ToolBar toolbar;
Canvas canvas;
ToolItem itemBack, itemForward;
Label status;
ProgressBar progressBar;
SWTError error = null;
static final String[] imageLocations = { "eclipse01.bmp", "eclipse02.bmp",
"eclipse03.bmp", "eclipse04.bmp", "eclipse05.bmp", "eclipse06.bmp",
"eclipse07.bmp", "eclipse08.bmp", "eclipse09.bmp", "eclipse10.bmp",
"eclipse11.bmp", "eclipse12.bmp", };
static final String iconLocation = "document.gif";
public SWTBrowserDemo(Composite parent, boolean top) {
this.parent = parent;
try {
browser = new Browser(parent, SWT.BORDER);
} catch (SWTError e) {
error = e;
/* Browser widget could not be instantiated */
parent.setLayout(new FillLayout());
Label label = new Label(parent, SWT.CENTER | SWT.WRAP);
label.setText(getResourceString("BrowserNotCreated"));
parent.layout(true);
return;
}
initResources();
final Display display = parent.getDisplay();
browser.setData(
"org.eclipse.swt.examples.browserexample.BrowserApplication",
this);
browser.addOpenWindowListener(new OpenWindowListener() {
public void open(WindowEvent event) {
Shell shell = new Shell(display);
if (icon != null)
shell.setImage(icon);
shell.setLayout(new FillLayout());
SWTBrowserDemo app = new SWTBrowserDemo(shell, false);
app.setShellDecoration(icon, true);
event.browser = app.getBrowser();
}
});
if (top) {
browser.setUrl(getResourceString("Startup"));
show(false, null, null, true, true, true, true);
} else {
browser.addVisibilityWindowListener(new VisibilityWindowListener() {
public void hide(WindowEvent e) {
}
public void show(WindowEvent e) {
Browser browser = (Browser) e.widget;
SWTBrowserDemo app = (SWTBrowserDemo) browser
.getData("org.eclipse.swt.examples.browserexample.BrowserApplication");
app.show(true, e.location, e.size, e.addressBar, e.menuBar,
e.statusBar, e.toolBar);
}
});
browser.addCloseWindowListener(new CloseWindowListener() {
public void close(WindowEvent event) {
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
shell.close();
}
});
}
}
/**
* Disposes of all resources associated with a particular instance of the
* BrowserApplication.
*/
public void dispose() {
freeResources();
}
/**
* Gets a string from the resource bundle. We don"t want to crash because of
* a missing String. Returns the key if not found.
*/
static String getResourceString(String key) {
return key;
}
public SWTError getError() {
return error;
}
public Browser getBrowser() {
return browser;
}
public void setShellDecoration(Image icon, boolean title) {
this.icon = icon;
this.title = title;
}
void show(boolean owned, Point location, Point size, boolean addressBar,
boolean menuBar, boolean statusBar, boolean toolBar) {
final Shell shell = browser.getShell();
if (owned) {
if (location != null)
shell.setLocation(location);
if (size != null)
shell.setSize(shell.ruputeSize(size.x, size.y));
}
FormData data = null;
if (toolBar) {
toolbar = new ToolBar(parent, SWT.NONE);
data = new FormData();
data.top = new FormAttachment(0, 5);
toolbar.setLayoutData(data);
itemBack = new ToolItem(toolbar, SWT.PUSH);
itemBack.setText(getResourceString("Back"));
itemForward = new ToolItem(toolbar, SWT.PUSH);
itemForward.setText(getResourceString("Forward"));
final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
itemStop.setText(getResourceString("Stop"));
final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
itemRefresh.setText(getResourceString("Refresh"));
final ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText(getResourceString("Go"));
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem) event.widget;
if (item == itemBack)
browser.back();
else if (item == itemForward)
browser.forward();
else if (item == itemStop)
browser.stop();
else if (item == itemRefresh)
browser.refresh();
else if (item == itemGo)
browser.setUrl(locationBar.getText());
}
};
itemBack.addListener(SWT.Selection, listener);
itemForward.addListener(SWT.Selection, listener);
itemStop.addListener(SWT.Selection, listener);
itemRefresh.addListener(SWT.Selection, listener);
itemGo.addListener(SWT.Selection, listener);
canvas = new Canvas(parent, SWT.NO_BACKGROUND);
data = new FormData();
data.width = 24;
data.height = 24;
data.top = new FormAttachment(0, 5);
data.right = new FormAttachment(100, -5);
canvas.setLayoutData(data);
final Rectangle rect = images[0].getBounds();
canvas.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
Point pt = ((Canvas) e.widget).getSize();
e.gc.drawImage(images[index], 0, 0, rect.width,
rect.height, 0, 0, pt.x, pt.y);
}
});
canvas.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(getResourceString("Startup"));
}
});
final Display display = parent.getDisplay();
display.asyncExec(new Runnable() {
public void run() {
if (canvas.isDisposed())
return;
if (busy) {
index++;
if (index == images.length)
index = 0;
canvas.redraw();
}
display.timerExec(150, this);
}
});
}
if (addressBar) {
locationBar = new Text(parent, SWT.BORDER);
data = new FormData();
if (toolbar != null) {
data.top = new FormAttachment(toolbar, 0, SWT.TOP);
data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
} else {
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
}
locationBar.setLayoutData(data);
locationBar.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(locationBar.getText());
}
});
}
if (statusBar) {
status = new Label(parent, SWT.NONE);
progressBar = new ProgressBar(parent, SWT.NONE);
data = new FormData();
data.left = new FormAttachment(0, 5);
data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
data.bottom = new FormAttachment(100, -5);
status.setLayoutData(data);
data = new FormData();
data.right = new FormAttachment(100, -5);
data.bottom = new FormAttachment(100, -5);
progressBar.setLayoutData(data);
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
status.setText(event.text);
}
});
}
parent.setLayout(new FormLayout());
Control aboveBrowser = toolBar ? (Control) canvas
: (addressBar ? (Control) locationBar : null);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.top = aboveBrowser != null ? new FormAttachment(aboveBrowser, 5,
SWT.DEFAULT) : new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
data.bottom = status != null ? new FormAttachment(status, -5,
SWT.DEFAULT) : new FormAttachment(100, 0);
browser.setLayoutData(data);
if (statusBar || toolBar) {
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
if (event.total == 0)
return;
int ratio = event.current * 100 / event.total;
if (progressBar != null)
progressBar.setSelection(ratio);
busy = event.current != event.total;
if (!busy) {
index = 0;
if (canvas != null)
canvas.redraw();
}
}
public void completed(ProgressEvent event) {
if (progressBar != null)
progressBar.setSelection(0);
busy = false;
index = 0;
if (canvas != null) {
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
canvas.redraw();
}
}
});
}
if (addressBar || statusBar || toolBar) {
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
busy = true;
if (event.top && locationBar != null)
locationBar.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
}
if (title) {
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
shell.setText(event.title + " - "
+ getResourceString("window.title"));
}
});
}
parent.layout(true);
if (owned)
shell.open();
}
/**
* Grabs input focus.
*/
public void focus() {
if (locationBar != null)
locationBar.setFocus();
else if (browser != null)
browser.setFocus();
else
parent.setFocus();
}
/**
* Frees the resources
*/
void freeResources() {
if (images != null) {
for (int i = 0; i < images.length; ++i) {
final Image image = images[i];
if (image != null)
image.dispose();
}
images = null;
}
}
/**
* Loads the resources
*/
void initResources() {
final Class clazz = this.getClass();
try {
if (images == null) {
images = new Image[imageLocations.length];
for (int i = 0; i < imageLocations.length; ++i) {
InputStream sourceStream = clazz
.getResourceAsStream(imageLocations[i]);
ImageData source = new ImageData(sourceStream);
ImageData mask = source.getTransparencyMask();
images[i] = new Image(null, source, mask);
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
} catch (Throwable t) {
}
String error = "Unable to load resources";
freeResources();
throw new RuntimeException(error);
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText(getResourceString("window.title"));
InputStream stream = SWTBrowserDemo.class
.getResourceAsStream(iconLocation);
Image icon = new Image(display, stream);
shell.setImage(icon);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
SWTBrowserDemo app = new SWTBrowserDemo(shell, true);
app.setShellDecoration(icon, true);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
icon.dispose();
app.dispose();
display.dispose();
}
}
Bring up a browser
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
/*
* Browser example snippet: bring up a browser
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
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.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class BringUpBrowser {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
shell.setLayout(gridLayout);
ToolBar toolbar = new ToolBar(shell, SWT.NONE);
ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
itemBack.setText("Back");
ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
itemForward.setText("Forward");
ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
itemStop.setText("Stop");
ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
itemRefresh.setText("Refresh");
ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText("Go");
GridData data = new GridData();
data.horizontalSpan = 3;
toolbar.setLayoutData(data);
Label labelAddress = new Label(shell, SWT.NONE);
labelAddress.setText("Address");
final Text location = new Text(shell, SWT.BORDER);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.horizontalSpan = 2;
data.grabExcessHorizontalSpace = true;
location.setLayoutData(data);
final Browser browser = new Browser(shell, SWT.NONE);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
data.horizontalSpan = 3;
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
browser.setLayoutData(data);
final Label status = new Label(shell, SWT.NONE);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
status.setLayoutData(data);
final ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
data = new GridData();
data.horizontalAlignment = GridData.END;
progressBar.setLayoutData(data);
/* event handling */
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem) event.widget;
String string = item.getText();
if (string.equals("Back"))
browser.back();
else if (string.equals("Forward"))
browser.forward();
else if (string.equals("Stop"))
browser.stop();
else if (string.equals("Refresh"))
browser.refresh();
else if (string.equals("Go"))
browser.setUrl(location.getText());
}
};
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
if (event.total == 0)
return;
int ratio = event.current * 100 / event.total;
progressBar.setSelection(ratio);
}
public void completed(ProgressEvent event) {
progressBar.setSelection(0);
}
});
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
status.setText(event.text);
}
});
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
if (event.top)
location.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
itemBack.addListener(SWT.Selection, listener);
itemForward.addListener(SWT.Selection, listener);
itemStop.addListener(SWT.Selection, listener);
itemRefresh.addListener(SWT.Selection, listener);
itemGo.addListener(SWT.Selection, listener);
location.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(location.getText());
}
});
shell.open();
browser.setUrl("http://eclipse.org");
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
HTML Explorer
import java.io.File;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableColumn;
public class Explorer extends ApplicationWindow {
public Explorer() {
super(null);
}
protected Control createContents(Composite parent) {
SashForm sash_form = new SashForm(parent, SWT.HORIZONTAL | SWT.NULL);
TreeViewer tv = new TreeViewer(sash_form);
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput(new File("C:\\"));
final TableViewer tbv = new TableViewer(sash_form, SWT.BORDER);
tbv.setContentProvider(new FileTableContentProvider());
tbv.setLabelProvider(new FileTableLabelProvider());
TableColumn column = new TableColumn(tbv.getTable(), SWT.LEFT);
column.setText("Name");
column.setWidth(200);
tbv.getTable().setHeaderVisible(true);
tv.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event
.getSelection();
Object selected_file = selection.getFirstElement();
tbv.setInput(selected_file);
}
});
return sash_form;
}
public static void main(String[] args) {
Explorer w = new Explorer();
w.setBlockOnOpen(true);
w.open();
Display.getCurrent().dispose();
}
}
class FileTreeLabelProvider extends LabelProvider {
public String getText(Object element) {
return ((File) element).getName();
}
}
class FileTreeContentProvider implements ITreeContentProvider {
public Object[] getChildren(Object element) {
Object[] kids = ((File) element).listFiles();
return kids == null ? new Object[0] : kids;
}
public Object[] getElements(Object element) {
return getChildren(element);
}
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
public Object getParent(Object element) {
return null;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object old_input, Object new_input) {
}
}
class FileTableLabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int i) {
return ((File) obj).getName();
}
public void addListener(ILabelProviderListener ilabelproviderlistener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object obj, String s) {
return false;
}
public void removeListener(ILabelProviderListener ilabelproviderlistener) {
}
public Image getColumnImage(Object arg0, int arg1) {
return null;
}
}
class FileTableContentProvider implements IStructuredContentProvider {
public Object[] getElements(Object element) {
Object[] kids = null;
kids = ((File) element).listFiles();
return kids == null ? new Object[0] : kids;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object old_object, Object new_object) {
}
}
HTML Explorer based on JFace
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
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.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableColumn;
public class JFaceExplorer extends ApplicationWindow {
public JFaceExplorer() {
super(null);
addStatusLine();
}
protected Control createContents(Composite parent) {
getShell().setText("JFace File Explorer");
SashForm sash_form = new SashForm(parent, SWT.HORIZONTAL | SWT.NULL);
TreeViewer tv = new TreeViewer(sash_form);
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput(new File("C:\\"));
tv.addFilter(new AllowOnlyFoldersFilter());
final TableViewer tbv = new TableViewer(sash_form, SWT.BORDER
| SWT.FULL_SELECTION | SWT.MULTI);
tbv.setContentProvider(new FileTableContentProvider());
tbv.setLabelProvider(new FileTableLabelProvider());
tbv.setSorter(new FileSorter());
TableColumn column = new TableColumn(tbv.getTable(), SWT.LEFT);
column.setText("Name");
column.setWidth(200);
column = new TableColumn(tbv.getTable(), SWT.RIGHT);
column.setText("Size");
column.setWidth(100);
tbv.getTable().setHeaderVisible(true);
tv.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event
.getSelection();
Object selected_file = selection.getFirstElement();
tbv.setInput(selected_file);
}
});
tbv.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event
.getSelection();
setStatus("Number of items selected is " + selection.size());
}
});
return sash_form;
}
public static void main(String[] args) {
JFaceExplorer w = new JFaceExplorer();
w.setBlockOnOpen(true);
w.open();
Display.getCurrent().dispose();
}
}
class Util {
private static ImageRegistry image_registry;
public static URL newURL(String url_name) {
try {
return new URL(url_name);
} catch (MalformedURLException e) {
throw new RuntimeException("Malformed URL " + url_name, e);
}
}
public static ImageRegistry getImageRegistry() {
if (image_registry == null) {
image_registry = new ImageRegistry();
image_registry.put("folder", ImageDescriptor
.createFromURL(newURL("file:icons/folder.gif")));
image_registry.put("file", ImageDescriptor
.createFromURL(newURL("file:icons/file.gif")));
}
return image_registry;
}
}
class FileTreeLabelProvider extends LabelProvider {
public String getText(Object element) {
return ((File) element).getName();
}
public Image getImage(Object element) {
if (((File) element).isDirectory()) {
return Util.getImageRegistry().get("folder");
} else {
return Util.getImageRegistry().get("file");
}
}
}
class FileTreeContentProvider implements ITreeContentProvider {
public Object[] getChildren(Object element) {
Object[] kids = ((File) element).listFiles();
return kids == null ? new Object[0] : kids;
}
public Object[] getElements(Object element) {
return getChildren(element);
}
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
public Object getParent(Object element) {
return ((File) element).getParent();
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object old_input, Object new_input) {
}
}
class FileTableLabelProvider implements ITableLabelProvider {
public String getColumnText(Object element, int column_index) {
if (column_index == 0) {
return ((File) element).getName();
}
if (column_index == 1) {
return "" + ((File) element).length();
}
return "";
}
public void addListener(ILabelProviderListener ilabelproviderlistener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object obj, String s) {
return false;
}
public void removeListener(ILabelProviderListener ilabelproviderlistener) {
}
public Image getColumnImage(Object element, int column_index) {
if (column_index != 0) {
return null;
}
if (((File) element).isDirectory()) {
return Util.getImageRegistry().get("folder");
} else {
return Util.getImageRegistry().get("file");
}
}
}
class FileTableContentProvider implements IStructuredContentProvider {
public Object[] getElements(Object element) {
Object[] kids = null;
kids = ((File) element).listFiles();
return kids == null ? new Object[0] : kids;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object old_object, Object new_object) {
}
}
class FileSorter extends ViewerSorter {
public int category(Object element) {
return ((File) element).isDirectory() ? 0 : 1;
}
}
class AllowOnlyFoldersFilter extends ViewerFilter {
public boolean select(Viewer viewer, Object parent, Object element) {
return ((File) element).isDirectory();
}
}
Implements a web browser
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class implements a web browser
*/
public class SimpleBrowser {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Simple Browser");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window"s contents
*
* @param shell the main window
*/
private void createContents(Shell shell) {
shell.setLayout(new FormLayout());
// Create the composite to hold the buttons and text field
Composite controls = new Composite(shell, SWT.NONE);
FormData data = new FormData();
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
controls.setLayoutData(data);
// Create the web browser
final Browser browser = new Browser(shell, SWT.NONE);
data = new FormData();
data.top = new FormAttachment(controls);
data.bottom = new FormAttachment(100, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
browser.setLayoutData(data);
// Create the controls and wire them to the browser
controls.setLayout(new GridLayout(6, false));
// Create the back button
Button button = new Button(controls, SWT.PUSH);
button.setText("Back");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.back();
}
});
// Create the forward button
button = new Button(controls, SWT.PUSH);
button.setText("Forward");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.forward();
}
});
// Create the refresh button
button = new Button(controls, SWT.PUSH);
button.setText("Refresh");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.refresh();
}
});
// Create the stop button
button = new Button(controls, SWT.PUSH);
button.setText("Stop");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.stop();
}
});
// Create the address entry field and set focus to it
final Text url = new Text(controls, SWT.BORDER);
url.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
url.setFocus();
// Create the go button
button = new Button(controls, SWT.PUSH);
button.setText("Go");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.setUrl(url.getText());
}
});
// Allow users to hit enter to go to the typed URL
shell.setDefaultButton(button);
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new SimpleBrowser().run();
}
}
Implements a web browser 2
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class implements a web browser
*/
public class AdvancedBrowser {
// The "at rest" text of the throbber
private static final String AT_REST = "Ready";
/**
* Runs the application
*
* @param location the initial location to display
*/
public void run(String location) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Advanced Browser");
createContents(shell, location);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window"s contents
*
* @param shell the main window
* @param location the initial location
*/
public void createContents(Shell shell, String location) {
shell.setLayout(new FormLayout());
// Create the composite to hold the buttons and text field
Composite controls = new Composite(shell, SWT.NONE);
FormData data = new FormData();
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
controls.setLayoutData(data);
// Create the status bar
Label status = new Label(shell, SWT.NONE);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
data.bottom = new FormAttachment(100, 0);
status.setLayoutData(data);
// Create the web browser
final Browser browser = new Browser(shell, SWT.BORDER);
data = new FormData();
data.top = new FormAttachment(controls);
data.bottom = new FormAttachment(status);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
browser.setLayoutData(data);
// Create the controls and wire them to the browser
controls.setLayout(new GridLayout(7, false));
// Create the back button
Button button = new Button(controls, SWT.PUSH);
button.setText("Back");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.back();
}
});
// Create the forward button
button = new Button(controls, SWT.PUSH);
button.setText("Forward");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.forward();
}
});
// Create the refresh button
button = new Button(controls, SWT.PUSH);
button.setText("Refresh");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.refresh();
}
});
// Create the stop button
button = new Button(controls, SWT.PUSH);
button.setText("Stop");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.stop();
}
});
// Create the address entry field and set focus to it
final Text url = new Text(controls, SWT.BORDER);
url.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
url.setFocus();
// Create the go button
button = new Button(controls, SWT.PUSH);
button.setText("Go");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.setUrl(url.getText());
}
});
// Create the animated "throbber"
Label throbber = new Label(controls, SWT.NONE);
throbber.setText(AT_REST);
// Allow users to hit enter to go to the typed URL
shell.setDefaultButton(button);
// Add event handlers
browser.addCloseWindowListener(new AdvancedCloseWindowListener());
browser.addLocationListener(new AdvancedLocationListener(url));
browser.addProgressListener(new AdvancedProgressListener(throbber));
browser.addStatusTextListener(new AdvancedStatusTextListener(status));
// Go to the initial URL
if (location != null) {
browser.setUrl(location);
}
}
/**
* This class implements a CloseWindowListener for AdvancedBrowser
*/
class AdvancedCloseWindowListener implements CloseWindowListener {
/**
* Called when the parent window should be closed
*/
public void close(WindowEvent event) {
// Close the parent window
((Browser) event.widget).getShell().close();
}
}
/**
* This class implements a LocationListener for AdvancedBrowser
*/
class AdvancedLocationListener implements LocationListener {
// The address text box to update
private Text location;
/**
* Constructs an AdvancedLocationListener
*
* @param text the address text box to update
*/
public AdvancedLocationListener(Text text) {
// Store the address box for updates
location = text;
}
/**
* Called before the location changes
*
* @param event the event
*/
public void changing(LocationEvent event) {
// Show the location that"s loading
location.setText("Loading " + event.location + "...");
}
/**
* Called after the location changes
*
* @param event the event
*/
public void changed(LocationEvent event) {
// Show the loaded location
location.setText(event.location);
}
}
/**
* This class implements a ProgressListener for AdvancedBrowser
*/
class AdvancedProgressListener implements ProgressListener {
// The label on which to report progress
private Label progress;
/**
* Constructs an AdvancedProgressListener
*
* @param label the label on which to report progress
*/
public AdvancedProgressListener(Label label) {
// Store the label on which to report updates
progress = label;
}
/**
* Called when progress is made
*
* @param event the event
*/
public void changed(ProgressEvent event) {
// Avoid divide-by-zero
if (event.total != 0) {
// Calculate a percentage and display it
int percent = (int) (event.current / event.total);
progress.setText(percent + "%");
} else {
// Since we can"t calculate a percent, show confusion :-)
progress.setText("???");
}
}
/**
* Called when load is complete
*
* @param event the event
*/
public void completed(ProgressEvent event) {
// Reset to the "at rest" message
progress.setText(AT_REST);
}
}
/**
* This class implements a StatusTextListener for AdvancedBrowser
*/
class AdvancedStatusTextListener implements StatusTextListener {
// The label on which to report status
private Label status;
/**
* Constructs an AdvancedStatusTextListener
*
* @param label the label on which to report status
*/
public AdvancedStatusTextListener(Label label) {
// Store the label on which to report status
status = label;
}
/**
* Called when the status changes
*
* @param event the event
*/
public void changed(StatusTextEvent event) {
// Report the status
status.setText(event.text);
}
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new AdvancedBrowser().run(args.length == 0 ? null : args[0]);
}
}
Modify HTML title tag
/*
* Browser example snippet: modify HTML title tag
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Snippet159 {
public static void main(String[] args) {
final String newTitle = "New Value for Title";
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Browser browser = new Browser(shell, SWT.NONE);
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
System.out.println("TitleEvent: " + event.title);
shell.setText(event.title);
}
});
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
}
public void completed(ProgressEvent event) {
/*
* Set HTML title tag using JavaScript and DOM when page has
* been loaded
*/
boolean result = browser.execute("document.title="" + newTitle
+ """);
if (!result) {
/*
* Script may fail or may not be supported on certain
* platforms.
*/
System.out.println("Script was not executed.");
}
}
});
/* Load an HTML document */
browser.setUrl("http://www.eclipse.org");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Query DOM node value
/*
* Browser example snippet: query DOM node value
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Snippet160 {
public static void main(String[] args) {
final String html = "<html><title>Snippet</title><body><p id="myid">Best Friends</p><p id="myid2">Cat and Dog</p></body></html>";
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Browser browser = new Browser(shell, SWT.NONE);
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
browser.setData("query", event.text);
}
});
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
}
public void completed(ProgressEvent event) {
/*
* Use JavaScript to query the desired node content through the
* Document Object Model
*
* Assign result to the window property status to pass the
* result to the StatusTextListener This trick is required since
* <code>execute</code> does not return the <code>String</code>
* directly.
*/
boolean result = browser
.execute("window.status=document.getElementById("myid").childNodes[0].nodeValue;");
if (!result) {
/*
* Script may fail or may not be supported on certain
* platforms.
*/
System.out.println("Script was not executed.");
return;
}
String value = (String) browser.getData("query");
System.out.println("Node value: " + value);
}
});
/* Load an HTML document */
browser.setText(html);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Render HTML that includes relative links from memory
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
/*
* Browser example snippet: render HTML that includes relative links from memory
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class RenderHTML {
public static void main(String[] args) {
/* Relative links: use the HTML base tag */
String html = "<html><head>"
+ "<base href=\"http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/\" >"
+ "<title>HTML Test</title></head>"
+ "<body></body></html>";
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
browser.setText(html);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
SWT Browser
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-4-10 1:15:03 by JACK $Id$
*
******************************************************************************/
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.CloseWindowListener;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
public class SWTBrowser {
Display display = new Display();
Shell shell = new Shell(display);
Text textLocation;
Browser browser;
Label labelStatus;
public SWTBrowser() {
shell.setLayout(new GridLayout());
ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.RIGHT);
final ToolBarManager manager = new ToolBarManager(toolBar);
Composite compositeLocation = new Composite(shell, SWT.NULL);
compositeLocation.setLayout(new GridLayout(3, false));
compositeLocation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label labelAddress = new Label(compositeLocation, SWT.NULL);
labelAddress.setText("Address");
textLocation = new Text(compositeLocation, SWT.SINGLE | SWT.BORDER);
textLocation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Button buttonGo = new Button(compositeLocation, SWT.NULL);
buttonGo.setImage(new Image(shell.getDisplay(), "jexp.gif"));
browser = new Browser(shell, SWT.BORDER);
browser.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite compositeStatus = new Composite(shell, SWT.NULL);
compositeStatus.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
compositeStatus.setLayout(new GridLayout(2, false));
labelStatus = new Label(compositeStatus, SWT.NULL);
labelStatus.setText("Ready");
labelStatus.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final ProgressBar progressBar =
new ProgressBar(compositeStatus, SWT.SMOOTH);
Listener openURLListener = new Listener() {
public void handleEvent(Event event) {
browser.setUrl(textLocation.getText());
}
};
buttonGo.addListener(SWT.Selection, openURLListener);
textLocation.addListener(SWT.DefaultSelection, openURLListener);
// Adds tool bar items using actions.
final Action actionBackward =
new Action(
"&Backword",
ImageDescriptor.createFromFile(
null,
"jexp.gif")) {
public void run() {
browser.back();
}
};
actionBackward.setEnabled(false); // action is disabled at start up.
final Action actionForward =
new Action(
"&Forward",
ImageDescriptor.createFromFile(
null,
"icons/web/forward.gif")) {
public void run() {
browser.forward();
}
};
actionForward.setEnabled(false); // action is disabled at start up.
Action actionStop =
new Action(
"&Stop",
ImageDescriptor.createFromFile(null, "icons/web/stop.gif")) {
public void run() {
browser.stop();
}
};
Action actionRefresh =
new Action(
"&Refresh",
ImageDescriptor.createFromFile(
null,
"icons/web/refresh.gif")) {
public void run() {
browser.refresh();
}
};
Action actionHome =
new Action(
"&Home",
ImageDescriptor.createFromFile(null, "icons/web/home.gif")) {
public void run() {
browser.setUrl("http://www.eclipse.org");
}
};
manager.add(actionBackward);
manager.add(actionForward);
manager.add(actionStop);
manager.add(actionRefresh);
manager.add(actionHome);
manager.update(true);
toolBar.pack();
browser.addLocationListener(new LocationListener() {
public void changing(LocationEvent event) {
// Displays the new location in the text field.
textLocation.setText(event.location);
}
public void changed(LocationEvent event) {
// Update tool bar items.
actionBackward.setEnabled(browser.isBackEnabled());
actionForward.setEnabled(browser.isForwardEnabled());
manager.update(false);
}
});
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
progressBar.setMaximum(event.total);
progressBar.setSelection(event.current);
}
public void completed(ProgressEvent event) {
progressBar.setSelection(0);
}
});
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
labelStatus.setText(event.text);
}
});
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
shell.setText(event.title + " - powered by SWT");
}
});
initialize(display, browser);
shell.setSize(500, 400);
shell.open();
//textUser.forceFocus();
//browser.setText(
// "<html><body>" + "<h1>SWT & JFace </h1>" + "</body/html>");
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
static void initialize(final Display display, Browser browser) {
browser.addOpenWindowListener(new OpenWindowListener() {
public void open(WindowEvent event) {
Shell shell = new Shell(display);
shell.setText("New Window");
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
initialize(display, browser);
event.browser = browser;
}
});
browser.addVisibilityWindowListener(new VisibilityWindowListener() {
public void hide(WindowEvent event) {
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
shell.setVisible(false);
}
public void show(WindowEvent event) {
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
if (event.location != null)
shell.setLocation(event.location);
if (event.size != null) {
Point size = event.size;
shell.setSize(shell.ruputeSize(size.x, size.y));
}
shell.open();
}
});
browser.addCloseWindowListener(new CloseWindowListener() {
public void close(WindowEvent event) {
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
shell.close();
}
});
}
private void init() {
}
public static void main(String[] args) {
new SWTBrowser();
}
}
SWT Browser Example
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-4-10 20:04:08 by JACK $Id$
*
******************************************************************************/
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.eclipse.swt.browser.CloseWindowListener;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.StatusTextEvent;
import org.eclipse.swt.browser.StatusTextListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class BrowserExample {
//static ResourceBundle resourceBundle =
// ResourceBundle.getBundle("examples_browser");
int index;
boolean busy;
Image images[];
Text location;
Browser browser;
static final String[] imageLocations = { "eclipse01.bmp", "eclipse02.bmp",
"eclipse03.bmp", "eclipse04.bmp", "eclipse05.bmp", "eclipse06.bmp",
"eclipse07.bmp", "eclipse08.bmp", "eclipse09.bmp", "eclipse10.bmp",
"eclipse11.bmp", "eclipse12.bmp", };
static final String iconLocation = "jexp.gif";
/**
* Creates an instance of a ControlExample embedded inside the supplied
* parent Composite.
*
* @param parent
* the container of the example
*/
public BrowserExample(Composite parent) {
final Display display = parent.getDisplay();
FormLayout layout = new FormLayout();
parent.setLayout(layout);
ToolBar toolbar = new ToolBar(parent, SWT.NONE);
final ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
itemBack.setText(getResourceString("Back"));
final ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
itemForward.setText(getResourceString("Forward"));
final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
itemStop.setText(getResourceString("Stop"));
final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
itemRefresh.setText(getResourceString("Refresh"));
final ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText(getResourceString("Go"));
location = new Text(parent, SWT.BORDER);
images = new Image[] { new Image(display, "jexp.gif") };
final Canvas canvas = new Canvas(parent, SWT.NO_BACKGROUND);
final Rectangle rect = images[0].getBounds();
canvas.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
Point pt = canvas.getSize();
e.gc.drawImage(images[index], 0, 0, rect.width, rect.height, 0,
0, pt.x, pt.y);
}
});
canvas.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(getResourceString("Startup"));
}
});
display.asyncExec(new Runnable() {
public void run() {
if (canvas.isDisposed())
return;
if (busy) {
index++;
if (index == images.length)
index = 0;
canvas.redraw();
}
display.timerExec(150, this);
}
});
final Label status = new Label(parent, SWT.NONE);
final ProgressBar progressBar = new ProgressBar(parent, SWT.NONE);
FormData data = new FormData();
data.top = new FormAttachment(0, 5);
toolbar.setLayoutData(data);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
data.top = new FormAttachment(canvas, 5, SWT.DEFAULT);
data.bottom = new FormAttachment(status, -5, SWT.DEFAULT);
try {
browser = new Browser(parent, SWT.NONE);
browser.setLayoutData(data);
} catch (SWTError e) {
/* Browser widget could not be instantiated */
Label label = new Label(parent, SWT.CENTER | SWT.WRAP);
label.setText(getResourceString("BrowserNotCreated"));
label.setLayoutData(data);
}
data = new FormData();
data.width = 24;
data.height = 24;
data.top = new FormAttachment(0, 5);
data.right = new FormAttachment(100, -5);
canvas.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(toolbar, 0, SWT.TOP);
data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
location.setLayoutData(data);
data = new FormData();
data.left = new FormAttachment(0, 5);
data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
data.bottom = new FormAttachment(100, -5);
status.setLayoutData(data);
data = new FormData();
data.right = new FormAttachment(100, -5);
data.bottom = new FormAttachment(100, -5);
progressBar.setLayoutData(data);
if (browser != null) {
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem) event.widget;
if (item == itemBack)
browser.back();
else if (item == itemForward)
browser.forward();
else if (item == itemStop)
browser.stop();
else if (item == itemRefresh)
browser.refresh();
else if (item == itemGo)
browser.setUrl(location.getText());
}
};
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
busy = true;
if (event.top)
location.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
if (event.total == 0)
return;
int ratio = event.current * 100 / event.total;
progressBar.setSelection(ratio);
busy = event.current != event.total;
if (!busy) {
index = 0;
canvas.redraw();
}
}
public void completed(ProgressEvent event) {
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
progressBar.setSelection(0);
busy = false;
index = 0;
canvas.redraw();
}
});
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
status.setText(event.text);
}
});
if (parent instanceof Shell) {
final Shell shell = (Shell) parent;
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
shell.setText(event.title + " - "
+ getResourceString("window.title"));
}
});
}
itemBack.addListener(SWT.Selection, listener);
itemForward.addListener(SWT.Selection, listener);
itemStop.addListener(SWT.Selection, listener);
itemRefresh.addListener(SWT.Selection, listener);
itemGo.addListener(SWT.Selection, listener);
location.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(location.getText());
}
});
initialize(display, browser);
browser.setUrl(getResourceString("Startup"));
}
}
/**
* Gets a string from the resource bundle. We don"t want to crash because of
* a missing String. Returns the key if not found.
*/
static String getResourceString(String key) {
try {
return "key";
} catch (MissingResourceException e) {
return key;
} catch (NullPointerException e) {
return "!" + key + "!";
}
}
/**
* Gets a string from the resource bundle and binds it with the given
* arguments. If the key is not found, return the key.
*/
static String getResourceString(String key, Object[] args) {
try {
return MessageFormat.format(getResourceString(key), args);
} catch (MissingResourceException e) {
return key;
} catch (NullPointerException e) {
return "!" + key + "!";
}
}
static void initialize(final Display display, Browser browser) {
browser.addOpenWindowListener(new OpenWindowListener() {
public void open(WindowEvent event) {
System.out.println("Open");
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
initialize(display, browser);
event.browser = browser;
}
});
browser.addVisibilityWindowListener(new VisibilityWindowListener() {
public void hide(WindowEvent event) {
}
public void show(WindowEvent event) {
System.out.println("Show");
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
if (event.location != null)
shell.setLocation(event.location);
if (event.size != null) {
Point size = event.size;
shell.setSize(shell.ruputeSize(size.x, size.y));
}
shell.open();
}
});
browser.addCloseWindowListener(new CloseWindowListener() {
public void close(WindowEvent event) {
System.out.println("Close");
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
shell.close();
}
});
}
/**
* Disposes of all resources associated with a particular instance of the
* BrowserExample.
*/
public void dispose() {
freeResources();
}
/**
* Frees the resources
*/
void freeResources() {
if (images != null) {
for (int i = 0; i < images.length; ++i) {
final Image image = images[i];
if (image != null)
image.dispose();
}
images = null;
}
}
/**
* Grabs input focus.
*/
public void setFocus() {
location.setFocus();
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Browser example");
BrowserExample instance = new BrowserExample(shell);
Image icon = new Image(display, "jexp.gif");
shell.setImage(icon);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
icon.dispose();
instance.dispose();
display.dispose();
}
}
Uses a web browser to display
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class uses a web browser to display Slashdot"s home page
*/
public class ShowSlashdot {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Slashdot");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window"s contents
*
* @param shell the main window
*/
private void createContents(Shell shell) {
shell.setLayout(new FillLayout());
// Create a web browser
Browser browser = new Browser(shell, SWT.NONE);
// Navigate to Slashdot
browser.setUrl("http://www.jexp.ru");
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new ShowSlashdot().run();
}
}
Web Browser Composite
/*
SWT/JFace in Action
GUI Design with Eclipse 3.0
Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic
ISBN: 1932394273
Publisher: Manning
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Text;
public class Ch12WebBrowserComposite extends Composite {
private Browser browser;
public Ch12WebBrowserComposite(Composite parent) {
super(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, true);
setLayout(layout);
browser = new Browser(this, SWT.NONE);
GridData layoutData = new GridData(GridData.FILL_BOTH);
layoutData.horizontalSpan = 2;
layoutData.verticalSpan = 2;
browser.setLayoutData(layoutData);
browser.setUrl("http://www.slashdot.org");
final Text text = new Text(this, SWT.SINGLE);
layoutData = new GridData(GridData.FILL_HORIZONTAL);
text.setLayoutData(layoutData);
Button openButton = new Button(this, SWT.PUSH);
openButton.setText("Open");
openButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
browser.setUrl(text.getText());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Button backButton = new Button(this, SWT.PUSH);
backButton.setText("Back");
backButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
browser.back();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Button forwardButton = new Button(this, SWT.PUSH);
forwardButton.setText("Forward");
forwardButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
browser.forward();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
}