How to show up an image with swt in java?

十年热恋 提交于 2019-12-12 10:56:54

问题


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
}

回答1:


See the SWT-Snippets for examples. This one uses an image label

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



回答2:


You are missing one thing in your code. Event Handler for 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 :)

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

}


来源:https://stackoverflow.com/questions/4447455/how-to-show-up-an-image-with-swt-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!