如何在Java中使用SWT显示图像?

6

我尝试了以下内容,但没有得到任何结果:

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
}

你似乎没有实际显示任何内容... - Robert
我想展示图片... - lex
2个回答

7

请参考SWT-Snippets获取示例。 这个示例使用了图像标签。

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

试一下这段代码,它会完全按照你的要求执行。不要被标签搞混了 :) - the.duckman

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接