Java/SWT JFace Eclipse/ProgressBar
Содержание
A progress bar dialog
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
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.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
/**
* progress bar dialog.
* the first, you must know your app execute times,
* you need implement two method:
*
* process(int times);
* initGuage();
*
* you can implements method:
*
* cleanUp()
* doBefore()
* doAfter()
* @author yin_zhiguo
* yin_zhiguo@hotmail.ru
*
*/
public abstract class ProgressBarDialog extends Dialog {
private Label processMessageLabel; //info of process finish
private Button cancelButton; //cancel button
private Composite cancelComposite;
private Label lineLabel;//
private Composite progressBarComposite;//
private CLabel message;//
private ProgressBar progressBar = null; //
private Object result; //
private Shell shell; //
private Display display = null;
protected volatile boolean isClosed = false;//closed state
protected int executeTime = 50;//process times
protected String processMessage = "process......";//procress info
protected String shellTitle = "Progress..."; //
protected Image processImage = SWTUtil.getImageOfMessage();//image
protected boolean mayCancel = true; //cancel
protected int processBarStyle = SWT.SMOOTH; //process bar style
public void setMayCancel(boolean mayCancel) {
this.mayCancel = mayCancel;
}
public void setExecuteTime(int executeTime) {
this.executeTime = executeTime;
}
public void setProcessImage(Image processImage) {
this.processImage = processImage;
}
public void setProcessMessage(String processInfo) {
this.processMessage = processInfo;
}
public ProgressBarDialog(Shell parent) {
super(parent);
}
public abstract void initGuage();
public Object open() {
createContents(); //create window
shell.open();
shell.layout();
//start work
new ProcessThread(executeTime).start();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
protected void createContents() {
shell = new Shell(getParent(), SWT.TITLE | SWT.PRIMARY_MODAL);
display = shell.getDisplay();
final GridLayout gridLayout = new GridLayout();
gridLayout.verticalSpacing = 10;
shell.setLayout(gridLayout);
shell.setSize(483, 181);
shell.setText(shellTitle);
final Composite composite = new Composite(shell, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
composite.setLayout(new GridLayout());
message = new CLabel(composite, SWT.NONE);
message.setImage(processImage);
message.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
message.setText(processMessage);
progressBarComposite = new Composite(shell, SWT.NONE);
progressBarComposite.setLayoutData(new GridData(GridData.FILL,
GridData.CENTER, false, false));
progressBarComposite.setLayout(new FillLayout());
progressBar = new ProgressBar(progressBarComposite, processBarStyle);
progressBar.setMaximum(executeTime);
processMessageLabel = new Label(shell, SWT.NONE);
processMessageLabel.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false));
lineLabel = new Label(shell, SWT.HORIZONTAL | SWT.SEPARATOR);
lineLabel.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false));
cancelComposite = new Composite(shell, SWT.NONE);
cancelComposite.setLayoutData(new GridData(GridData.END,
GridData.CENTER, false, false));
final GridLayout gridLayout_1 = new GridLayout();
gridLayout_1.numColumns = 2;
cancelComposite.setLayout(gridLayout_1);
cancelButton = new Button(cancelComposite, SWT.NONE);
cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
isClosed = true;
//System.out.println(isClosed);
}
});
cancelButton.setLayoutData(new GridData(78, SWT.DEFAULT));
cancelButton.setText("cancel");
cancelButton.setEnabled(this.mayCancel);
}
protected abstract String process(int times);
protected void cleanUp()
{
}
protected void doBefore()
{
}
protected void doAfter()
{
}
class ProcessThread extends Thread {
private int max = 0;
private volatile boolean shouldStop = false;
ProcessThread(int max) {
this.max = max;
}
public void run() {
doBefore();
for (final int[] i = new int[] {1}; i[0] <= max; i[0]++)
{
//
final String info = process(i[0]);
if (display.isDisposed()) {
return;
}
display.syncExec(new Runnable() {
public void run() {
if (progressBar.isDisposed()) {
return;
}
//
processMessageLabel.setText(info);
//
progressBar.setSelection(i[0]);
//
if (i[0] == max || isClosed) {
if (isClosed) {
shouldStop = true;//
cleanUp();//
}
shell.close();//
}
}
});
if (shouldStop) {
break;
}
}
doAfter();
}
}
public void setShellTitle(String shellTitle) {
this.shellTitle = shellTitle;
}
public void setProcessBarStyle(boolean pStyle) {
if(pStyle)
this.processBarStyle = SWT.SMOOTH;
else
this.processBarStyle = SWT.NONE;
}
}
class DemoProgressBar extends ProgressBarDialog {
private String[] info = null;
public DemoProgressBar(Shell parent) {
super(parent);
}
@Override
public void initGuage() {
info = new String[100];
for (int i = 0; i < info.length; i++) {
info[i] = "process task " + i + ".";
}
this.setExecuteTime(100);
this.setMayCancel(true);
this.setProcessMessage("please waiting....");
this.setShellTitle("Demo");
}
@Override
protected String process(int arg0) {
try{
Thread.sleep((long)(Math.random() * 300));
}catch(Exception e){e.printStackTrace();}
return info[arg0 - 1];
}
}
class SWTUtil {
private static ImageRegistry imageRegistry = new ImageRegistry();
private static Clipboard clipboard = new Clipboard(Display.getCurrent());
private static final String ___IMAGE_Of_MESSAGE = "";
static{
imageRegistry.put(___IMAGE_Of_MESSAGE, ImageDescriptor.createFromURL(newURL("file:icons/info2.gif")));
}
private SWTUtil(){}
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 void registryImage(String id, String urlName)
{
imageRegistry.put(id, ImageDescriptor.createFromURL(newURL(urlName)));
}
public static Image getImage(String id)
{
return imageRegistry.get(id);
}
public static Clipboard getClipboard() {
return clipboard;
}
public static Image getImageOfMessage()
{
return imageRegistry.get(___IMAGE_Of_MESSAGE);
}
}
class PBDialogDemo extends Shell {
public static void main(String args[]) {
try {
Display display = Display.getDefault();
PBDialogDemo shell = new PBDialogDemo(display, SWT.SHELL_TRIM);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public PBDialogDemo(Display display, int style) {
super(display, style);
createContents();
}
protected void createContents() {
setText("ProgressBar Dialog");
setSize(218, 98);
setLayout(new FillLayout());
final Button openProgressbarDialogButton = new Button(this, SWT.NONE);
openProgressbarDialogButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DemoProgressBar dpb = new DemoProgressBar(PBDialogDemo.this);
dpb.initGuage();
dpb.open();
}
});
openProgressbarDialogButton.setText("Open ProgressBar Dialog");
}
protected void checkSubclass() {
}
}
Count Numbers
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-3-31 1:19:00 by JACK
* $Id$
*
*****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class CountNumbers {
Display display = new Display();
Shell shell = new Shell(display);
Button button;
ProgressBar progressBar;
public CountNumbers() {
GridLayout gridLayout = new GridLayout(1, true);
shell.setLayout(gridLayout);
button = new Button(shell, SWT.BORDER);
button.setText("Start to count");
progressBar = new ProgressBar(shell, SWT.SMOOTH);
progressBar.setMinimum(0);
progressBar.setMaximum(10);
final Thread countThread = new Thread(){
public void run() {
for(int i=0; i<=10; i++) {
final int num = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
shell.getDisplay().asyncExec(new Runnable(){
public void run() {
if(button.isDisposed() || progressBar.isDisposed())
return;
button.setText("Counting: " + num);
progressBar.setSelection(num);
//progressBar.redraw();
}
});
}
}
};
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
button.setEnabled(false);
countThread.start();
}
});
progressBar.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
System.out.println("PAINT");
// string to draw.
String string = (progressBar.getSelection() * 1.0 /(progressBar.getMaximum()-progressBar.getMinimum()) * 100) + "%";
Point point = progressBar.getSize();
Font font = new Font(shell.getDisplay(),"Courier",10,SWT.BOLD);
e.gc.setFont(font);
e.gc.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
FontMetrics fontMetrics = e.gc.getFontMetrics();
int stringWidth = fontMetrics.getAverageCharWidth() * string.length();
int stringHeight = fontMetrics.getHeight();
e.gc.drawString(string, (point.x-stringWidth)/2 , (point.y-stringHeight)/2, true);
font.dispose();
}
});
button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
progressBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
shell.setSize(300, 100);
shell.open();
//textUser.forceFocus();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
private void init() {
}
public static void main(String[] args) {
new CountNumbers();
}
}
Demonstrates ProgressBar
//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.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This class demonstrates ProgressBar
*/
public class ProgressBarExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
// Create a smooth progress bar
ProgressBar pb1 = new ProgressBar(shell, SWT.HORIZONTAL | SWT.SMOOTH);
pb1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
pb1.setMinimum(0);
pb1.setMaximum(30);
// Create an indeterminate progress bar
ProgressBar pb2 = new ProgressBar(shell, SWT.HORIZONTAL | SWT.INDETERMINATE);
pb2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Start the first progress bar
new LongRunningOperation(display, pb1).start();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
/**
* This class simulates a long running operation
*/
class LongRunningOperation extends Thread {
private Display display;
private ProgressBar progressBar;
public LongRunningOperation(Display display, ProgressBar progressBar) {
this.display = display;
this.progressBar = progressBar;
}
public void run() {
// Perform work here--this operation just sleeps
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
}
display.asyncExec(new Runnable() {
public void run() {
if (progressBar.isDisposed()) return;
// Increment the progress bar
progressBar.setSelection(progressBar.getSelection() + 1);
}
});
}
}
}
ProgressBar Example
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class ProgressBarExample {
Display d;
Shell s;
ProgressBarExample() {
d = new Display();
s = new Shell(d);
s.setSize(250, 250);
s.setText("A ProgressBar Example");
final ProgressBar pb = new ProgressBar(s, SWT.HORIZONTAL);
pb.setMinimum(0);
pb.setMaximum(100);
pb.setSelection(50);
pb.setBounds(10, 10, 200, 20);
s.open();
while (!s.isDisposed()) {
if (!d.readAndDispatch())
d.sleep();
}
d.dispose();
}
public static void main() {
new ProgressBarExample();
}
}
ProgressBar Examples
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-3-31 0:13:36 by JACK
* $Id$
*
*****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class ProgressBarExamples {
Display display = new Display();
Shell shell = new Shell(display);
public ProgressBarExamples() {
init();
ProgressBar pb1 = new ProgressBar(shell, SWT.NULL);
final ProgressBar pb2 = new ProgressBar(shell, SWT.SMOOTH);
ProgressBar pb3 = new ProgressBar(shell, SWT.INDETERMINATE);
// pb2.addPaintListener(new PaintListener() {
// public void paintControl(PaintEvent e) {
// Point point = pb2.getSize();
//
// Font font = new Font(shell.getDisplay(),"Courier",10,SWT.BOLD);
// e.gc.setFont(font);
// e.gc.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
//
// FontMetrics fontMetrics = e.gc.getFontMetrics();
// int stringWidth = fontMetrics.getAverageCharWidth() * 4;
// int stringHeight = fontMetrics.getHeight();
//
// e.gc.drawString("60%", (point.x-stringWidth)/2 , (point.y-stringHeight)/2, true);
// font.dispose();
// }
// });
pb1.setSelection(60);
pb2.setSelection(60);
pb1.setBounds(100, 10, 200, 20);
pb2.setBounds(100, 40, 200, 20);
//pb3.setBounds(100, 70, 200, 20);
Label label = new Label(shell, SWT.NULL);
label.setText("(default)");
Label label2 = new Label(shell, SWT.NULL);
label2.setText("SWT.SMOOTH");
label.setAlignment(SWT.RIGHT);
label2.setAlignment(SWT.RIGHT);
label.setBounds(10, 10, 80, 20);
label2.setBounds(10, 40, 80, 20);
shell.pack();
shell.open();
//textUser.forceFocus();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
private void init() {
}
public static void main(String[] args) {
new ProgressBarExamples();
}
}
Update a progress bar (from the UI thread)
/*
* ProgressBar example snippet: update a progress bar (from the UI thread)
*
* 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.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class Snippet57 {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
ProgressBar bar = new ProgressBar (shell, SWT.SMOOTH);
bar.setBounds (10, 10, 200, 32);
shell.open ();
for (int i=0; i<=bar.getMaximum (); i++) {
try {Thread.sleep (100);} catch (Throwable th) {}
bar.setSelection (i);
}
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
Update a SWT progress bar (from another thread)
/*
* ProgressBar example snippet: update a progress bar (from another thread)
*
* 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.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
public class Snippet56 {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
final ProgressBar bar = new ProgressBar(shell, SWT.SMOOTH);
bar.setBounds(10, 10, 200, 32);
shell.open();
final int maximum = bar.getMaximum();
new Thread() {
public void run() {
for (final int[] i = new int[1]; i[0] <= maximum; i[0]++) {
try {
Thread.sleep(100);
} catch (Throwable th) {
}
if (display.isDisposed())
return;
display.asyncExec(new Runnable() {
public void run() {
if (bar.isDisposed())
return;
bar.setSelection(i[0]);
}
});
}
}
}.start();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}