使用SWT

时间:2016-05-19 20:35:35

标签: java eclipse-plugin swt

我在bytearray中有一个BMP。我想使用SWT在Eclipse插件中显示BMP。

如果我想使用swing显示BMP,可以按如下方式进行:

    BufferedImage bufferedImage = null;
    try {
        bufferedImage = ImageIO.read(new ByteArrayInputStream(getLocalByteArray()));
    } catch (IOException ex) {

    }

    JLabel jLabel = new JLabel(new ImageIcon(bufferedImage));

    JPanel jPanel = new JPanel();
    jPanel.add(jLabel);
    this.add(jPanel);

更新: BMP将表示为字节数组。这是先决条件。

如何使用SWT在Eclipse插件中执行此操作?注意我正在使用Perspective。

3 个答案:

答案 0 :(得分:2)

可以直接从输入流创建SWT Image。支持多种数据格式,包括Windows格式的BMP。

例如:

Image image = new Image( display, new ByteArrayInputStream( ... ) );

然后可以在Label上设置生成的图像,或在其他地方使用。

答案 1 :(得分:1)

您只需在Image构造函数中指定文件,然后将其设置为Label

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    Label label = new Label(shell, SWT.NONE);
    Image image = new Image(display, "image.bmp");
    label.setImage(image);

    shell.pack();
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();

    image.dispose();
}

请记住,您必须自己dispose()图像,以免造成内存泄漏。

答案 2 :(得分:0)

好的 - 我明白了。由于代码很短,我已经包含了上下文:

public void createPartControl(Composite parent) {
    try {
        BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(getLocalByteArray()));
        ImageData imageData = new ImageData(inputStream);
        Image image = ImageDescriptor.createFromImageData(imageData).createImage();


        // Create the canvas for drawing
        Canvas canvas = new Canvas( parent, SWT.NONE);
        canvas.addPaintListener( new PaintListener() {
        public void paintControl(PaintEvent e) {
        GC gc = e.gc;
        gc.drawImage( image,10,10);
        }
        });