import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.events.*; /** * A tiny image viewer adapted from an example at : * * http://www.cs.sbcc.net/~sstrenn/cs145/cs145.html * */ public class SwtImageViewer { Shell shell; Composite clientArea; Image image; public static void main(String[] args) { new SwtImageViewer(); } public SwtImageViewer() { createShell(); shell.open(); run(); close(); } /** * Main processing method for the SWTImageViewerApp object */ public void run() { Display display = shell.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /* * Free the allocated resources. */ public void close() { if (shell != null && !shell.isDisposed()) { shell.dispose(); } } /** * Setup the main window */ private void createShell() { shell = new Shell(); shell.setText("SWT Test Image Viewer"); GridLayout layout = new GridLayout(); layout.numColumns = 1; shell.setSize(500, 500); shell.setLayout(layout); createMenuBar(shell); createClientArea(shell); shell.layout(true); } void createClientArea(Shell shell) { clientArea = new Composite(shell, SWT.BORDER); GridData spec = new GridData(); spec.horizontalAlignment = spec.FILL; spec.grabExcessHorizontalSpace = true; spec.verticalAlignment = spec.FILL; spec.grabExcessVerticalSpace = true; clientArea.setLayoutData(spec); GridLayout layout = new GridLayout(); layout.numColumns = 1; clientArea.setLayout(layout); clientArea.addListener(SWT.Paint, new Listener() { public void handleEvent(Event e) { if (image != null) { e.gc.drawImage(image, 0, 0); } } }); } private void createMenuBar(Shell shell) { Menu bar = new Menu(shell, SWT.BAR); shell.setMenuBar(bar); MenuItem fileItem = new MenuItem(bar, SWT.CASCADE); fileItem.setText("File"); fileItem.setMenu(createFileMenu()); } Menu createFileMenu() { Menu bar = shell.getMenuBar(); Menu menu = new Menu(bar); MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Open"); item.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { fileOpen_Click(); } }); new MenuItem(menu, SWT.SEPARATOR); item = new MenuItem(menu, SWT.PUSH); item.setText("Quit"); item.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { close(); } }); return menu; } void fileOpen_Click() { try { FileDialog fileChooser = new FileDialog(shell, SWT.OPEN); fileChooser.setFilterExtensions(new String[]{"*.bmp; *.gif; *.ico; *.jpg; *.pcx; *.png; *.tif", "*.bmp", "*.gif", "*.ico", "*.jpg", "*.pcx", "*.png", "*.tif"}); fileChooser.setFilterNames(new String[]{" (bmp, gif, ico, jpg, pcx, png, tif)", "BMP (*.bmp)", "GIF (*.gif)", "ICO (*.ico)", "JPEG (*.jpg)", "PCX (*.pcx)", "PNG (*.png)", "TIFF (*.tif)"}); String filename = fileChooser.open(); image = new Image(shell.getDisplay(), filename); clientArea.redraw(); } catch (Exception ex) { ex.printStackTrace(); } } }