SWT | GUI-Thread

Code:
package Test;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;


public class Threads {
	
	public static void main(String[] args)
	{
		// Shell wird erzeugt und mittig positioniert
		// ------------------------------------------
		final Display display = new Display();
		final Shell shell = new Shell(display);
		
		shell.setText("Threads");
		shell.setSize(200,200);
		Monitor pMonitor = display.getPrimaryMonitor();
		Rectangle bounds = pMonitor.getBounds();
		Rectangle rect = shell.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		shell.setLocation(x, y);
		// ------------------------------------------
		
		// Shellunterteilung wird erzeugt
		// ------------------------------
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 1;
		
		shell.setLayout(gridLayout1);
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		// ------------------------------
		
		//Button fürs Testen
		//------------------
		Button B_letztenfertig = new Button(shell,SWT.BORDER);
		B_letztenfertig.setText("Start");
		//------------------
		
		//Listener fürs Fertig markieren
		//------------------------------
		B_letztenfertig.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				//-----------------------------
				new Thread() {
		            public void run() {
		                Runnable r = new Runnable(){
		                    public void run(){
		                 		//Hier was Threadlastiges
		                    }
		                };
		                   
		                        display.asyncExec(r);
		            }
		        }.start();
		        //-----------------------------
			}});
		//------------------------------
		
		// Shell wird geöffnet
		// -------------------
		shell.open();
		// -------------------
		
		//--------------------
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		//--------------------
	}

}

Hier mal Beispielcode, wie ich vorgehe :)
 
Hallo, ich poste hier nochmal ein komplettes Beispiel:

Java:
package Test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.Shell;

public class Threads {
	
	public static void main(String[] args)
	{
		// Shell wird erzeugt und mittig positioniert
		// ------------------------------------------
		final Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setSize(200,200);
		// ------------------------------------------
		
		// Shellunterteilung wird erzeugt
		// ------------------------------
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 1;
		
		shell.setLayout(gridLayout1);
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		// ------------------------------
		
		//Button fürs Testen
		//------------------
		final Button B_Start = new Button(shell,SWT.BORDER);
		B_Start.setText("Start [0]");
		B_Start.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_FILL));
		//------------------
		
		//Listener fürs Fertig markieren
		//------------------------------
		B_Start.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				//-----------------------------
				new Thread() {
		            public void run() {
		                Runnable r = new Runnable(){
		                    public void run(){
		                 		try {
									laderunter(B_Start);
								} catch (IOException e) {
									e.printStackTrace();
								}
		                    }
		                };
		                   
		                        display.asyncExec(r);
		            }
		        }.start();
		        //-----------------------------
			}});
		//------------------------------
		
		// Shell wird geöffnet
		// -------------------
		shell.open();
		// -------------------
		
		//--------------------
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		//--------------------
	}
	
	static void laderunter(Button B_Start) throws IOException
	{
		B_Start.setText("Go [1]");
		  final URL url = new URL("http://speedtest.qsc.de/10MB.qsc");
		  final URLConnection conn = url.openConnection();
		  final InputStream is = new BufferedInputStream(conn.getInputStream());
		  final OutputStream os =
		        new BufferedOutputStream(new FileOutputStream("10MB.qsc"));
		  byte[] chunk = new byte[1024];
		  int chunkSize;
		  while ((chunkSize = is.read(chunk)) != -1) {
		    os.write(chunk, 0, chunkSize);
		  }
		  os.flush(); // Necessary for Java < 6
		  os.close();
		  is.close();
		  
		  B_Start.setText("End [" + "2" + "]");
	}

}

Achtung: bei schnellen DSL-Leitungen wird das file u.U. so schnell geladen, das man nichts merkt. dann einfach die Zeile

Java:
 final URL url = new URL("http://speedtest.qsc.de/10MB.qsc");

durch

Java:
 final URL url = new URL("http://speedtest.qsc.de/500MB.qsc");
ersetzen.
 
Zuletzt bearbeitet:
Hi,
also deine Oberfläche kann sich mit deinem Code eigtl. nur aufhängen, da du den Download im GUI-Thread laufen lässt. Du darfst nur den Status der GUI im GUI-Thread ändern. Nicht gleich den ganzen Prozess ausführen.
Java:
public class SWTThreads
{
	public static void main(final String[] args) {
		// Shell wird erzeugt und mittig positioniert
		// ------------------------------------------
		final Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setSize(200, 200);
		// ------------------------------------------
		
		// Shellunterteilung wird erzeugt
		// ------------------------------
		final GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 1;
		
		shell.setLayout(gridLayout1);
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		// ------------------------------
		
		// Button fürs Testen
		// ------------------
		final Button B_Start = new Button(shell, SWT.BORDER);
		B_Start.setText("Start [0]");
		B_Start
				.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL
				| GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL
				| GridData.VERTICAL_ALIGN_FILL));
		// ------------------
		
		// Listener fürs Fertig markieren
		// ------------------------------
		B_Start.addSelectionListener(new SelectionAdapter()
						{
			@Override
			public void widgetSelected(final SelectionEvent event) {
				// -----------------------------
				new Thread()
								{
					@Override
					public void run() {
						InputStream is = null;
						OutputStream os = null;
						try {
							final URL url = new URL("http://speedtest.qsc.de/10MB.qsc");
							final URLConnection conn = url.openConnection();
							
							conn.setUseCaches(false);
							conn.setDoInput(true);
							final int contentLength = conn.getContentLength();
							
							is = conn.getInputStream();
							os = new FileOutputStream("10MB.qsc");
							
							final byte[] chunk = new byte[1024];
							int chunkSize;
							int readedContentLength = 0;
							while((chunkSize = is.read(chunk)) != -1) {
								os.write(chunk, 0, chunkSize);
								
								readedContentLength += chunkSize;
								final double percentProgress = readedContentLength / contentLength
										* 100;
								
								final Runnable r1 = new Runnable()
																		{
									public void run() {
										B_Start.setText("Progress in % = " + percentProgress);
									}
								};
								display.asyncExec(r1);
							}
							os.flush(); // Necessary for Java < 6
						} catch(final Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if(os != null)
									os.close();
							} catch(final IOException e) {
								e.printStackTrace();
							}
							try {
								if(is != null)
									is.close();
							} catch(final IOException e) {
								e.printStackTrace();
							}
						}
					}
				}.start();
				// -----------------------------
			}
		});
		// ------------------------------
		
		// Shell wird geöffnet
		// -------------------
		shell.open();
		// -------------------
		
		// --------------------
		while(!shell.isDisposed()) {
			if(!display.readAndDispatch()) {
				display.sleep();
			}
		}
		// --------------------
	}
}

p.s.: Ich konnte den Code leider nicht testen. Sollte aber funktionieren.

Gruß

Fabio
 

Neue Beiträge

Zurück