簡明現代魔法 -> Java編程語言 -> SWT之路:SWT圖像顯示
SWT之路:SWT圖像顯示
2009-10-03
程序演示
還是先用SWT Desiner創建界面程序。然后創建一個Display對象和Image對象,和一個GC對象。類org.eclipse.swt.graphics.GC是一個封裝了所有可執行的繪圖操作的圖形上下文(Graphics Context)。然后以Display和圖片路徑創建Image對象,再調用gc.drawImage();就可以顯示圖片了。
程序代碼
package SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class showImages {
protected Shell shell;
public static Display myDisplay;
public static boolean internalCall = false;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
internalCall = true;
myDisplay = new Display();
try {
showImages window = new showImages();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents(myDisplay);
Image img = new Image(display, "images/3.jpg");
shell.open();
GC gc = new GC(shell);
gc.drawImage(img, 0, 0);
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
img.dispose();
if (internalCall) display.dispose();
}
/**
* Create contents of the window.
*/
protected void createContents(Display display) {
myDisplay = display;
shell = new Shell();
shell.setSize(520, 280);
shell.setText("圖像顯示");
}
}
一旦你創建了一個GC,你就有責任通過它的dispose方法釋放它的資源。一個由應用程序創建的GC需要立即被繪制,然后盡快釋放掉。這是因為每個GC都需要一個底層的系統資源,而在某些操作系統中這些資源是稀缺的,像Win98就只允許同時創建五個GC對象。