2010-12-15 57 views
5

我尝试如下,不拿出任何东西:如何用java中的swt显示图像?

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

它看起来并不像你实际显示什么... – Robert 2010-12-15 07:01:13

+0

我想显示图像。 .. – lex 2010-12-15 07:05:02

回答

5

的例子见SWT-SnippetsThis one使用图片标签

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

但我想在一个弹出窗口中显示图像,而不是标签。 – lex 2010-12-15 08:16:01

+0

尝试一下代码,它确实是你想要的。不要被标签弄糊涂:) – 2010-12-15 09:29:26

+0

我试过了代码,没有图像弹出来.. – lex 2010-12-15 11:28:40

2

您在代码中缺少一件事。 事件处理程序的油漆。通常当你创建一个组件时,它会产生一个绘画事件。所有的绘图相关的东西都应该放进去。 你也无需显式地创建GC ..它配备了事件对象:)

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(); 
    } 

}