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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4447455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:37:04  来源:igfitidea点击:

How to show up an image with swt in java?

javaswt

提问by lex

My try as follows,which doesn't come up with anything:

我的尝试如下,但没有任何结果:

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
}

回答by stacker

See the SWT-Snippetsfor examples. This oneuses an image label

有关示例,请参阅SWT-Snippets这个使用图像标签

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

回答by Favonius

You are missing one thing in your code. Event Handlerfor paint. Normally when you create a component it generates a paint event. All the drawing related stuff should go in it. Also you need not to create the GC explicitly.. It comes with the event object :)

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

}