2010-12-15 27 views
5

Mi intento de la siguiente manera, que no viene a nada:¿Cómo mostrar una imagen con swt en java?

public static void main(String[] args) { 
    Display display = new Display(); 
    Shell shell = new Shell(display); 

    Image image = new Image(display, 
     "D:/topic.png"); 
    GC gc = new GC(image); 
    gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE)); 
    gc.drawText("I've been drawn on",0,0,true); 
    gc.dispose(); 

    shell.pack(); 
    shell.open(); 

    while (!shell.isDisposed()) { 
     if (!display.readAndDispatch()) { 
      display.sleep(); 
     } 
    } 
    display.dispose(); 
    // TODO Auto-generated method stub 
} 
+0

No se ve como si estuviera realmente mostrar nada ... – Robert

+0

Quiero mostrar la imagen. .. – lex

Respuesta

5

Véase el SWT-Snippets de ejemplos. This one utiliza una etiqueta de imagen

Shell shell = new Shell (display); 
Label label = new Label (shell, SWT.BORDER); 
label.setImage (image); 
+0

Pero quiero mostrar la imagen en una ventana emergente, no como etiqueta. – lex

+0

Pruebe el código, hace exactamente lo que quiere. No se confunda con la etiqueta :) –

+0

Probé el código, no aparece ninguna imagen .. – lex

2

Usted se echa en falta una cosa en su código. Manejador de eventos para pintura. Normalmente cuando creas un componente genera un evento de pintura. Todas las cosas relacionadas con el dibujo deberían ir en él. También es necesario no crear el GC explícitamente .. Viene con el objeto de evento :)

import org.eclipse.swt.*; 
import org.eclipse.swt.graphics.*; 
import org.eclipse.swt.layout.*; 
import org.eclipse.swt.widgets.*; 

public class ImageX 
{ 
    public static void main (String [] args) 
    { 
     Display display = new Display(); 
     Shell shell = new Shell (display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED); 
     shell.setLayout(new FillLayout()); 
     final Image image = new Image(display, "C:\\temp\\flyimage1.png"); 

     shell.addListener (SWT.Paint, new Listener() 
     { 
      public void handleEvent (Event e) { 
       GC gc = e.gc; 
       int x = 10, y = 10; 
       gc.drawImage (image, x, y); 
       gc.dispose(); 
      } 
     }); 

     shell.setSize (600, 400); 
     shell.open(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) 
       display.sleep(); 
     } 

     if(image != null && !image.isDisposed()) 
      image.dispose(); 
     display.dispose(); 
    } 

} 
Cuestiones relacionadas