2012-12-30 72 views
2

我目前正在使用SWT和Eclipse的WindowBuilder製作一個獨立的應用程序(而不是eclipse插件),並且我正在測試在複合材料中放置圖像,以便用它來輕鬆地將圖像放入我的複合材料中,嘗試繪製圖像,它會引發IllegalArgumentException。我不知道發生了什麼,我正在尋找解釋/替代方案。發生了什麼,我將如何解決這個問題?SWT:組合內的圖像;獲取IllegalArgumentException

如果我註釋掉e.gc.drawImage這一行,沒什麼更多,它不會拋出異常。

這裏是一個的給我的錯誤代碼:

import org.eclipse.swt.SWT; 
import org.eclipse.swt.layout.FillLayout; 
import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Shell; 

public class GUI { 
    public static final Display display = Display.getDefault();; 
    private final Shell shell; 

    public GUI() { 
     shell = new Shell(display); 
     shell.setLayout(new FillLayout(SWT.HORIZONTAL)); 
    } 

    public static void main(String[] args) { 
     GUI window = new GUI(); 
     window.open(); 
    } 

    public void open() { 
     createContents(); 
     shell.open(); 
     shell.layout(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) { 
       display.sleep(); 
      } 
     } 
    } 

    private void createContents() { 
     shell.setSize(450, 300); 

     ImageTest img = new ImageTest(shell, SWT.NONE); 
    } 
} 

import org.eclipse.swt.graphics.Image; 
import org.eclipse.swt.widgets.Composite; 
import org.eclipse.swt.events.PaintListener; 
import org.eclipse.swt.events.PaintEvent; 
import org.eclipse.swt.layout.FillLayout; 
import org.eclipse.swt.SWT; 
import org.eclipse.swt.widgets.Canvas; 

public class ImageTest extends Composite { 
    public ImageTest(Composite parent, int style) { 
     super(parent, style); 
     setLayout(new FillLayout(SWT.HORIZONTAL)); 

     final Image img = new Image(GUI.display, "img.gif"); 

      // I tried drawing the image to both a canvas and the composite its self. Same outcome. 
     Canvas canvas = new Canvas(this, SWT.NONE); 
     canvas.addPaintListener(new PaintListener() { 
      public void paintControl(PaintEvent e) { 
       e.gc.drawImage(img, 0, 0); // If I comment this out, it runs fine. 
      } 
     }); 

     img.dispose(); 
    } 

    @Override 
    protected void checkSubclass() {} 
} 

任何幫助,將不勝感激。

回答

3

當paintControl試圖繪製它時,你會得到錯誤,因爲你的圖像被放置。在paint listener有機會被調用之前,您可以自己將它置於ImageTest構造函數的末尾。

您可避免通過使img類的成員變量,然後重寫處置methos做清理:

@Override 
public void dispose() { 
    this.img.dispose(); 
    super.dispose(); 
} 

不要忘了刪除線

img.dispose(); 

從您的構造函數。

1

GC.drawImage API文檔說在下列情況下會拋出IllegalArgumentException。可能性是圖像對象爲空。

IllegalArgumentException - 
ERROR_NULL_ARGUMENT - if the image is null 
ERROR_INVALID_ARGUMENT - if the image has been disposed 
ERROR_INVALID_ARGUMENT - if the given coordinates are outside the bounds of the image