如何在java中用swt显示图像?

时间:2010-12-15 06:57:38

标签: 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
}

2 个答案:

答案 0 :(得分:5)

有关示例,请参阅SWT-SnippetsThis one使用图片标签

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

答案 1 :(得分:2)

您的代码中缺少一件事。油漆的事件处理程序。通常,当您创建组件时,它会生成一个paint事件。所有绘图相关的东西都应该放进去。 此外,您无需显式创建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 ();
    }

}