开发者

How to show up an image with swt in java?

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

public static void main(String[] args) {
    Disp开发者_运维知识库lay 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
}


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


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜