private boolean saveAs() { FileDialog saveDialog = new FileDialog(shell, SWT.SAVE); saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"}); saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "}); saveDialog.open(); String name = saveDialog.getFileName(); if (name.equals("")) return false; if (name.indexOf(".adr") != name.length() - 4) { name += ".adr"; } File file = new File(saveDialog.getFilterPath(), name); if (file.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO); box.setText(resAddressBook.getString("Save_as_title")); box.setMessage( resAddressBook.getString("File") + file.getName() + " " + resAddressBook.getString("Query_overwrite")); if (box.open() != SWT.YES) { return false; } } this.file = file; return save(); }
/** * Creates all the items located in the Search submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Search submenu. */ private void createSearchMenu(Menu menuBar) { // Search menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resMessages.getString("Search_menu_title")); Menu searchMenu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(searchMenu); // Search -> Find... item = new MenuItem(searchMenu, SWT.NULL); item.setText(resMessages.getString("Find")); item.setAccelerator(SWT.MOD1 + 'F'); item.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { searchDialog.setMatchCase(false); searchDialog.setMatchWord(false); searchDialog.setSearchDown(true); searchDialog.setSearchString(""); searchDialog.setSelectedSearchArea(0); searchDialog.open(); } }); // Search -> Find Next item = new MenuItem(searchMenu, SWT.NULL); item.setText(resMessages.getString("Find_next")); item.setAccelerator(SWT.F3); item.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { searchDialog.open(); } }); }
private void openAddressBook() { FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); fileDialog.setFilterExtensions(new String[] {"*.messages;", "*.*"}); fileDialog.setFilterNames( new String[] { resMessages.getString("Book_filter_name") + " (*.messages)", resMessages.getString("All_filter_name") + " (*.*)" }); String name = fileDialog.open(); openAddressBook(name); }
private boolean save() { if (file == null) return saveAs(); Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(waitCursor); TableItem[] items = table.getItems(); String[] lines = new String[items.length]; for (int i = 0; i < items.length; i++) { String[] itemText = new String[table.getColumnCount()]; for (int j = 0; j < itemText.length; j++) { itemText[j] = items[i].getText(j); } lines[i] = encodeLine(itemText); } FileWriter fileWriter = null; try { fileWriter = new FileWriter(file.getAbsolutePath(), false); for (int i = 0; i < lines.length; i++) { fileWriter.write(lines[i]); } } catch (FileNotFoundException e) { displayError(resMessages.getString("File_not_found") + "\n" + file.getName()); return false; } catch (IOException e) { displayError(resMessages.getString("IO_error_write") + "\n" + file.getName()); return false; } finally { shell.setCursor(null); waitCursor.dispose(); if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { displayError(resMessages.getString("IO_error_close") + "\n" + file.getName()); return false; } } } shell.setText(resMessages.getString("Title_bar") + file.getName()); isModified = false; return true; }
public Shell open(Display display) { shell = new Shell(display); shell.setLayout(new FillLayout()); shell.addShellListener( new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { e.doit = closeAddressBook(); } }); createMenuBar(); searchDialog = new SearchDialog(shell); searchDialog.setSearchAreaNames(columnNames); searchDialog.setSearchAreaLabel(resAddressBook.getString("Column")); searchDialog.addFindListener( new FindListener() { public boolean find() { return findEntry(); } }); table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); table.setHeaderVisible(true); table.setMenu(createPopUpMenu()); table.addSelectionListener( new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length > 0) editEntry(items[0]); } }); for (int i = 0; i < columnNames.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(columnNames[i]); column.setWidth(150); final int columnIndex = i; column.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { sort(columnIndex); } }); } newAddressBook(); shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300); shell.open(); return shell; }
private void launchEditor(TableItem item) { String theCommand = resUser.getString("Custom_editor"); theCommand = theCommand.replaceAll("%file%", item.getText(3)); theCommand = theCommand.replaceAll("%line%", item.getText(1)); theCommand = theCommand.replace('/', File.separatorChar); theCommand = theCommand.replaceAll("%slash%", "/"); try { Runtime.getRuntime().exec(theCommand); } catch (IOException e) { displayError("Error launching editor: " + e.getMessage()); } }
/** * Creates all the items located in the Help submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Help submenu. */ private void createHelpMenu(Menu menuBar) { // Help Menu MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resMessages.getString("Help_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); // Help -> About Text Editor MenuItem subItem = new MenuItem(menu, SWT.NULL); subItem.setText(resMessages.getString("About")); subItem.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { MessageBox box = new MessageBox(shell, SWT.NONE); box.setText(resMessages.getString("About_1") + shell.getText()); box.setMessage(shell.getText() + resMessages.getString("About_2")); box.open(); } }); }
private boolean closeAddressBook() { if (isModified) { // ask user if they want to save current address book MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO | SWT.CANCEL); box.setText(shell.getText()); box.setMessage(resAddressBook.getString("Close_save")); int choice = box.open(); if (choice == SWT.CANCEL) { return false; } else if (choice == SWT.YES) { if (!save()) return false; } } TableItem[] items = table.getItems(); for (int i = 0; i < items.length; i++) { items[i].dispose(); } return true; }
/** * Creates all the items located in the File submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the File submenu. */ private void createFileMenu(Menu menuBar) { // File menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("File_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); /** Adds a listener to handle enabling and disabling some items in the Edit submenu. */ menu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); items[1].setEnabled(table.getSelectionCount() != 0); // edit contact items[5].setEnabled((file != null) && isModified); // save items[6].setEnabled(table.getItemCount() != 0); // save as } }); // File -> New Contact MenuItem subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("New_contact")); subItem.setAccelerator(SWT.MOD1 + 'N'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { newEntry(); } }); subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Edit_contact")); subItem.setAccelerator(SWT.MOD1 + 'E'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); new MenuItem(menu, SWT.SEPARATOR); // File -> New Address Book subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("New_address_book")); subItem.setAccelerator(SWT.MOD1 + 'B'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (closeAddressBook()) { newAddressBook(); } } }); // File -> Open subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Open_address_book")); subItem.setAccelerator(SWT.MOD1 + 'O'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (closeAddressBook()) { openAddressBook(); } } }); // File -> Save. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Save_address_book")); subItem.setAccelerator(SWT.MOD1 + 'S'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { save(); } }); // File -> Save As. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Save_book_as")); subItem.setAccelerator(SWT.MOD1 + 'A'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveAs(); } }); new MenuItem(menu, SWT.SEPARATOR); // File -> Exit. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Exit")); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); }
/** * Creates all the items located in the Edit submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Edit submenu. * @see #createSortMenu() */ private MenuItem createEditMenu(Menu menuBar) { // Edit menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("Edit_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); /** Add a listener to handle enabling and disabling some items in the Edit submenu. */ menu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); int count = table.getSelectionCount(); items[0].setEnabled(count != 0); // edit items[1].setEnabled(count != 0); // copy items[2].setEnabled(copyBuffer != null); // paste items[3].setEnabled(count != 0); // delete items[5].setEnabled(table.getItemCount() != 0); // sort } }); // Edit -> Edit MenuItem subItem = new MenuItem(menu, SWT.PUSH); subItem.setText(resAddressBook.getString("Edit")); subItem.setAccelerator(SWT.MOD1 + 'E'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); // Edit -> Copy subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Copy")); subItem.setAccelerator(SWT.MOD1 + 'C'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; copyBuffer = new String[table.getColumnCount()]; for (int i = 0; i < copyBuffer.length; i++) { copyBuffer[i] = items[0].getText(i); } } }); // Edit -> Paste subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Paste")); subItem.setAccelerator(SWT.MOD1 + 'V'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (copyBuffer == null) return; TableItem item = new TableItem(table, SWT.NONE); item.setText(copyBuffer); isModified = true; } }); // Edit -> Delete subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Delete")); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; items[0].dispose(); isModified = true; } }); new MenuItem(menu, SWT.SEPARATOR); // Edit -> Sort(Cascade) subItem = new MenuItem(menu, SWT.CASCADE); subItem.setText(resAddressBook.getString("Sort")); Menu submenu = createSortMenu(); subItem.setMenu(submenu); return item; }
private void openAddressBook() { FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"}); fileDialog.setFilterNames( new String[] { resAddressBook.getString("Book_filter_name") + " (*.adr)", resAddressBook.getString("All_filter_name") + " (*.*)" }); String name = fileDialog.open(); if (name == null) return; File file = new File(name); if (!file.exists()) { displayError( resAddressBook.getString("File") + file.getName() + " " + resAddressBook.getString("Does_not_exist")); return; } Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); FileReader fileReader = null; BufferedReader bufferedReader = null; String[] data = new String[0]; try { fileReader = new FileReader(file.getAbsolutePath()); bufferedReader = new BufferedReader(fileReader); String nextLine = bufferedReader.readLine(); while (nextLine != null) { String[] newData = new String[data.length + 1]; System.arraycopy(data, 0, newData, 0, data.length); newData[data.length] = nextLine; data = newData; nextLine = bufferedReader.readLine(); } } catch (FileNotFoundException e) { displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName()); return; } catch (IOException e) { displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName()); return; } finally { shell.setCursor(null); if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName()); return; } } } String[][] tableInfo = new String[data.length][table.getColumnCount()]; int writeIndex = 0; for (int i = 0; i < data.length; i++) { String[] line = decodeLine(data[i]); if (line != null) tableInfo[writeIndex++] = line; } if (writeIndex != data.length) { String[][] result = new String[writeIndex][table.getColumnCount()]; System.arraycopy(tableInfo, 0, result, 0, writeIndex); tableInfo = result; } Arrays.sort(tableInfo, new RowComparator(0)); for (int i = 0; i < tableInfo.length; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(tableInfo[i]); } shell.setText(resAddressBook.getString("Title_bar") + fileDialog.getFileName()); isModified = false; this.file = file; }
private void openAddressBook(String name) { if (name == null) return; File file = new File(name); if (!file.exists()) { displayError( resMessages.getString("File") + file.getName() + " " + resMessages.getString("Does_not_exist")); return; } Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(waitCursor); FileReader fileReader = null; BufferedReader bufferedReader = null; String[] data = new String[0]; try { fileReader = new FileReader(file.getAbsolutePath()); bufferedReader = new BufferedReader(fileReader); String nextLine = bufferedReader.readLine(); while (nextLine != null) { String[] newData = new String[data.length + 1]; System.arraycopy(data, 0, newData, 0, data.length); newData[data.length] = nextLine; data = newData; nextLine = bufferedReader.readLine(); } } catch (FileNotFoundException e) { displayError(resMessages.getString("File_not_found") + "\n" + file.getName()); return; } catch (IOException e) { displayError(resMessages.getString("IO_error_read") + "\n" + file.getName()); return; } finally { shell.setCursor(null); waitCursor.dispose(); if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { displayError(resMessages.getString("IO_error_close") + "\n" + file.getName()); return; } } } String[][] tableInfo = new String[data.length][table.getColumnCount()]; for (int i = 0; i < data.length; i++) { tableInfo[i] = decodeLine(data[i]); } Arrays.sort(tableInfo, new RowComparator(0)); for (int i = 0; i < tableInfo.length; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(tableInfo[i]); } shell.setText(resMessages.getString("Title_bar") + file.getName()); isModified = false; this.file = file; }
/** * AddressBookExample is an example that uses <code>org.eclipse.swt</code> libraries to implement a * simple address book. This application has save, load, sorting, and searching functions common to * basic address books. */ public class AddressBook { private static ResourceBundle resAddressBook = ResourceBundle.getBundle("examples_addressbook"); private Shell shell; private Table table; private SearchDialog searchDialog; private File file; private boolean isModified; private String[] copyBuffer; private int lastSortColumn = -1; private static final String DELIMITER = "\t"; private static final String[] columnNames = { resAddressBook.getString("Last_name"), resAddressBook.getString("First_name"), resAddressBook.getString("Business_phone"), resAddressBook.getString("Home_phone"), resAddressBook.getString("Email"), resAddressBook.getString("Fax") }; public static void main(String[] args) { Display display = new Display(); AddressBook application = new AddressBook(); Shell shell = application.open(display); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } public Shell open(Display display) { shell = new Shell(display); shell.setLayout(new FillLayout()); shell.addShellListener( new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { e.doit = closeAddressBook(); } }); createMenuBar(); searchDialog = new SearchDialog(shell); searchDialog.setSearchAreaNames(columnNames); searchDialog.setSearchAreaLabel(resAddressBook.getString("Column")); searchDialog.addFindListener( new FindListener() { public boolean find() { return findEntry(); } }); table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); table.setHeaderVisible(true); table.setMenu(createPopUpMenu()); table.addSelectionListener( new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length > 0) editEntry(items[0]); } }); for (int i = 0; i < columnNames.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(columnNames[i]); column.setWidth(150); final int columnIndex = i; column.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { sort(columnIndex); } }); } newAddressBook(); shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300); shell.open(); return shell; } private boolean closeAddressBook() { if (isModified) { // ask user if they want to save current address book MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO | SWT.CANCEL); box.setText(shell.getText()); box.setMessage(resAddressBook.getString("Close_save")); int choice = box.open(); if (choice == SWT.CANCEL) { return false; } else if (choice == SWT.YES) { if (!save()) return false; } } TableItem[] items = table.getItems(); for (int i = 0; i < items.length; i++) { items[i].dispose(); } return true; } /** * Creates the menu at the top of the shell where most of the programs functionality is accessed. * * @return The <code>Menu</code> widget that was created */ private Menu createMenuBar() { Menu menuBar = new Menu(shell, SWT.BAR); shell.setMenuBar(menuBar); // create each header and subMenu for the menuBar createFileMenu(menuBar); createEditMenu(menuBar); createSearchMenu(menuBar); createHelpMenu(menuBar); return menuBar; } /** Converts an encoded <code>String</code> to a String array representing a table entry. */ private String[] decodeLine(String line) { if (line == null) return null; String[] parsedLine = new String[table.getColumnCount()]; for (int i = 0; i < parsedLine.length - 1; i++) { int index = line.indexOf(DELIMITER); if (index > -1) { parsedLine[i] = line.substring(0, index); line = line.substring(index + DELIMITER.length(), line.length()); } else { return null; } } if (line.indexOf(DELIMITER) != -1) return null; parsedLine[parsedLine.length - 1] = line; return parsedLine; } private void displayError(String msg) { MessageBox box = new MessageBox(shell, SWT.ICON_ERROR); box.setMessage(msg); box.open(); } private void editEntry(TableItem item) { DataEntryDialog dialog = new DataEntryDialog(shell); dialog.setLabels(columnNames); String[] values = new String[table.getColumnCount()]; for (int i = 0; i < values.length; i++) { values[i] = item.getText(i); } dialog.setValues(values); values = dialog.open(); if (values != null) { item.setText(values); isModified = true; } } private String encodeLine(String[] tableItems) { String line = ""; for (int i = 0; i < tableItems.length - 1; i++) { line += tableItems[i] + DELIMITER; } line += tableItems[tableItems.length - 1] + "\n"; return line; } private boolean findEntry() { Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); boolean matchCase = searchDialog.getMatchCase(); boolean matchWord = searchDialog.getMatchWord(); String searchString = searchDialog.getSearchString(); int column = searchDialog.getSelectedSearchArea(); searchString = matchCase ? searchString : searchString.toLowerCase(); boolean found = false; if (searchDialog.getSearchDown()) { for (int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) { if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)) { table.setSelection(i); break; } } } else { for (int i = table.getSelectionIndex() - 1; i > -1; i--) { if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)) { table.setSelection(i); break; } } } shell.setCursor(null); return found; } private boolean findMatch( String searchString, TableItem item, int column, boolean matchWord, boolean matchCase) { String tableText = matchCase ? item.getText(column) : item.getText(column).toLowerCase(); if (matchWord) { if (tableText != null && tableText.equals(searchString)) { return true; } } else { if (tableText != null && tableText.indexOf(searchString) != -1) { return true; } } return false; } private void newAddressBook() { shell.setText(resAddressBook.getString("Title_bar") + resAddressBook.getString("New_title")); file = null; isModified = false; } private void newEntry() { DataEntryDialog dialog = new DataEntryDialog(shell); dialog.setLabels(columnNames); String[] data = dialog.open(); if (data != null) { TableItem item = new TableItem(table, SWT.NONE); item.setText(data); isModified = true; } } private void openAddressBook() { FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"}); fileDialog.setFilterNames( new String[] { resAddressBook.getString("Book_filter_name") + " (*.adr)", resAddressBook.getString("All_filter_name") + " (*.*)" }); String name = fileDialog.open(); if (name == null) return; File file = new File(name); if (!file.exists()) { displayError( resAddressBook.getString("File") + file.getName() + " " + resAddressBook.getString("Does_not_exist")); return; } Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); FileReader fileReader = null; BufferedReader bufferedReader = null; String[] data = new String[0]; try { fileReader = new FileReader(file.getAbsolutePath()); bufferedReader = new BufferedReader(fileReader); String nextLine = bufferedReader.readLine(); while (nextLine != null) { String[] newData = new String[data.length + 1]; System.arraycopy(data, 0, newData, 0, data.length); newData[data.length] = nextLine; data = newData; nextLine = bufferedReader.readLine(); } } catch (FileNotFoundException e) { displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName()); return; } catch (IOException e) { displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName()); return; } finally { shell.setCursor(null); if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName()); return; } } } String[][] tableInfo = new String[data.length][table.getColumnCount()]; int writeIndex = 0; for (int i = 0; i < data.length; i++) { String[] line = decodeLine(data[i]); if (line != null) tableInfo[writeIndex++] = line; } if (writeIndex != data.length) { String[][] result = new String[writeIndex][table.getColumnCount()]; System.arraycopy(tableInfo, 0, result, 0, writeIndex); tableInfo = result; } Arrays.sort(tableInfo, new RowComparator(0)); for (int i = 0; i < tableInfo.length; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(tableInfo[i]); } shell.setText(resAddressBook.getString("Title_bar") + fileDialog.getFileName()); isModified = false; this.file = file; } private boolean save() { if (file == null) return saveAs(); Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(waitCursor); TableItem[] items = table.getItems(); String[] lines = new String[items.length]; for (int i = 0; i < items.length; i++) { String[] itemText = new String[table.getColumnCount()]; for (int j = 0; j < itemText.length; j++) { itemText[j] = items[i].getText(j); } lines[i] = encodeLine(itemText); } FileWriter fileWriter = null; try { fileWriter = new FileWriter(file.getAbsolutePath(), false); for (int i = 0; i < lines.length; i++) { fileWriter.write(lines[i]); } } catch (FileNotFoundException e) { displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName()); return false; } catch (IOException e) { displayError(resAddressBook.getString("IO_error_write") + "\n" + file.getName()); return false; } finally { shell.setCursor(null); if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName()); return false; } } } shell.setText(resAddressBook.getString("Title_bar") + file.getName()); isModified = false; return true; } private boolean saveAs() { FileDialog saveDialog = new FileDialog(shell, SWT.SAVE); saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"}); saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "}); saveDialog.open(); String name = saveDialog.getFileName(); if (name.equals("")) return false; if (name.indexOf(".adr") != name.length() - 4) { name += ".adr"; } File file = new File(saveDialog.getFilterPath(), name); if (file.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO); box.setText(resAddressBook.getString("Save_as_title")); box.setMessage( resAddressBook.getString("File") + file.getName() + " " + resAddressBook.getString("Query_overwrite")); if (box.open() != SWT.YES) { return false; } } this.file = file; return save(); } private void sort(int column) { if (table.getItemCount() <= 1) return; TableItem[] items = table.getItems(); String[][] data = new String[items.length][table.getColumnCount()]; for (int i = 0; i < items.length; i++) { for (int j = 0; j < table.getColumnCount(); j++) { data[i][j] = items[i].getText(j); } } Arrays.sort(data, new RowComparator(column)); if (lastSortColumn != column) { table.setSortColumn(table.getColumn(column)); table.setSortDirection(SWT.DOWN); for (int i = 0; i < data.length; i++) { items[i].setText(data[i]); } lastSortColumn = column; } else { // reverse order if the current column is selected again table.setSortDirection(SWT.UP); int j = data.length - 1; for (int i = 0; i < data.length; i++) { items[i].setText(data[j--]); } lastSortColumn = -1; } } /** * Creates all the items located in the File submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the File submenu. */ private void createFileMenu(Menu menuBar) { // File menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("File_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); /** Adds a listener to handle enabling and disabling some items in the Edit submenu. */ menu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); items[1].setEnabled(table.getSelectionCount() != 0); // edit contact items[5].setEnabled((file != null) && isModified); // save items[6].setEnabled(table.getItemCount() != 0); // save as } }); // File -> New Contact MenuItem subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("New_contact")); subItem.setAccelerator(SWT.MOD1 + 'N'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { newEntry(); } }); subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Edit_contact")); subItem.setAccelerator(SWT.MOD1 + 'E'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); new MenuItem(menu, SWT.SEPARATOR); // File -> New Address Book subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("New_address_book")); subItem.setAccelerator(SWT.MOD1 + 'B'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (closeAddressBook()) { newAddressBook(); } } }); // File -> Open subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Open_address_book")); subItem.setAccelerator(SWT.MOD1 + 'O'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (closeAddressBook()) { openAddressBook(); } } }); // File -> Save. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Save_address_book")); subItem.setAccelerator(SWT.MOD1 + 'S'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { save(); } }); // File -> Save As. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Save_book_as")); subItem.setAccelerator(SWT.MOD1 + 'A'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveAs(); } }); new MenuItem(menu, SWT.SEPARATOR); // File -> Exit. subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Exit")); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); } /** * Creates all the items located in the Edit submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Edit submenu. * @see #createSortMenu() */ private MenuItem createEditMenu(Menu menuBar) { // Edit menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("Edit_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); /** Add a listener to handle enabling and disabling some items in the Edit submenu. */ menu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); int count = table.getSelectionCount(); items[0].setEnabled(count != 0); // edit items[1].setEnabled(count != 0); // copy items[2].setEnabled(copyBuffer != null); // paste items[3].setEnabled(count != 0); // delete items[5].setEnabled(table.getItemCount() != 0); // sort } }); // Edit -> Edit MenuItem subItem = new MenuItem(menu, SWT.PUSH); subItem.setText(resAddressBook.getString("Edit")); subItem.setAccelerator(SWT.MOD1 + 'E'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); // Edit -> Copy subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Copy")); subItem.setAccelerator(SWT.MOD1 + 'C'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; copyBuffer = new String[table.getColumnCount()]; for (int i = 0; i < copyBuffer.length; i++) { copyBuffer[i] = items[0].getText(i); } } }); // Edit -> Paste subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Paste")); subItem.setAccelerator(SWT.MOD1 + 'V'); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (copyBuffer == null) return; TableItem item = new TableItem(table, SWT.NONE); item.setText(copyBuffer); isModified = true; } }); // Edit -> Delete subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("Delete")); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; items[0].dispose(); isModified = true; } }); new MenuItem(menu, SWT.SEPARATOR); // Edit -> Sort(Cascade) subItem = new MenuItem(menu, SWT.CASCADE); subItem.setText(resAddressBook.getString("Sort")); Menu submenu = createSortMenu(); subItem.setMenu(submenu); return item; } /** * Creates all the items located in the Sort cascading submenu and associate all the menu items * with their appropriate functions. * * @return Menu The cascading menu with all the sort menu items on it. */ private Menu createSortMenu() { Menu submenu = new Menu(shell, SWT.DROP_DOWN); MenuItem subitem; for (int i = 0; i < columnNames.length; i++) { subitem = new MenuItem(submenu, SWT.NONE); subitem.setText(columnNames[i]); final int column = i; subitem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { sort(column); } }); } return submenu; } /** * Creates all the items located in the Search submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Search submenu. */ private void createSearchMenu(Menu menuBar) { // Search menu. MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("Search_menu_title")); Menu searchMenu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(searchMenu); // Search -> Find... item = new MenuItem(searchMenu, SWT.NONE); item.setText(resAddressBook.getString("Find")); item.setAccelerator(SWT.MOD1 + 'F'); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { searchDialog.setMatchCase(false); searchDialog.setMatchWord(false); searchDialog.setSearchDown(true); searchDialog.setSearchString(""); searchDialog.setSelectedSearchArea(0); searchDialog.open(); } }); // Search -> Find Next item = new MenuItem(searchMenu, SWT.NONE); item.setText(resAddressBook.getString("Find_next")); item.setAccelerator(SWT.F3); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { searchDialog.open(); } }); } /** * Creates all items located in the popup menu and associates all the menu items with their * appropriate functions. * * @return Menu The created popup menu. */ private Menu createPopUpMenu() { Menu popUpMenu = new Menu(shell, SWT.POP_UP); /** Adds a listener to handle enabling and disabling some items in the Edit submenu. */ popUpMenu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); int count = table.getSelectionCount(); items[2].setEnabled(count != 0); // edit items[3].setEnabled(count != 0); // copy items[4].setEnabled(copyBuffer != null); // paste items[5].setEnabled(count != 0); // delete items[7].setEnabled(table.getItemCount() != 0); // find } }); // New MenuItem item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_new")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { newEntry(); } }); new MenuItem(popUpMenu, SWT.SEPARATOR); // Edit item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_edit")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); // Copy item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_copy")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; copyBuffer = new String[table.getColumnCount()]; for (int i = 0; i < copyBuffer.length; i++) { copyBuffer[i] = items[0].getText(i); } } }); // Paste item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_paste")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (copyBuffer == null) return; TableItem item = new TableItem(table, SWT.NONE); item.setText(copyBuffer); isModified = true; } }); // Delete item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_delete")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; items[0].dispose(); isModified = true; } }); new MenuItem(popUpMenu, SWT.SEPARATOR); // Find... item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_find")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { searchDialog.open(); } }); return popUpMenu; } /** * Creates all the items located in the Help submenu and associate all the menu items with their * appropriate functions. * * @param menuBar Menu the <code>Menu</code> that file contain the Help submenu. */ private void createHelpMenu(Menu menuBar) { // Help Menu MenuItem item = new MenuItem(menuBar, SWT.CASCADE); item.setText(resAddressBook.getString("Help_menu_title")); Menu menu = new Menu(shell, SWT.DROP_DOWN); item.setMenu(menu); // Help -> About Text Editor MenuItem subItem = new MenuItem(menu, SWT.NONE); subItem.setText(resAddressBook.getString("About")); subItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { MessageBox box = new MessageBox(shell, SWT.NONE); box.setText(resAddressBook.getString("About_1") + shell.getText()); box.setMessage(shell.getText() + resAddressBook.getString("About_2")); box.open(); } }); } /** To compare entries (rows) by the given column */ private class RowComparator implements Comparator<String[]> { private int column; /** * Constructs a RowComparator given the column index * * @param col The index (starting at zero) of the column */ public RowComparator(int col) { column = col; } /** * Compares two rows (type String[]) using the specified column entry. * * @param row1 First row to compare * @param row2 Second row to compare * @return negative if row1 less than row2, positive if row1 greater than row2, and zero if * equal. */ public int compare(String[] row1, String[] row2) { return row1[column].compareTo(row2[column]); } } }
private void newAddressBook() { shell.setText(resAddressBook.getString("Title_bar") + resAddressBook.getString("New_title")); file = null; isModified = false; }
public class JavaViewer { org.eclipse.swt.widgets.Shell shell; org.eclipse.swt.custom.StyledText text; org.eclipse.swt.examples.javaviewer.JavaLineStyler lineStyler = new org.eclipse.swt.examples.javaviewer.JavaLineStyler(); org.eclipse.swt.widgets.FileDialog fileDialog; static java.util.ResourceBundle resources = ResourceBundle.getBundle("examples_javaviewer"); org.eclipse.swt.widgets.Menu createFileMenu() { org.eclipse.swt.widgets.Menu bar = shell.getMenuBar(); org.eclipse.swt.widgets.Menu menu = new org.eclipse.swt.widgets.Menu(bar); org.eclipse.swt.widgets.MenuItem item; item = new org.eclipse.swt.widgets.MenuItem(menu, SWT.PUSH); item.setText(resources.getString("Open_menuitem")); item.setAccelerator(SWT.MOD1 + 'O'); item.addSelectionListener( new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent event) { openFile(); } }); item = new org.eclipse.swt.widgets.MenuItem(menu, SWT.PUSH); item.setText(resources.getString("Exit_menuitem")); item.addSelectionListener( new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { menuFileExit(); } }); return menu; } void createMenuBar() { org.eclipse.swt.widgets.Menu bar = new org.eclipse.swt.widgets.Menu(shell, SWT.BAR); shell.setMenuBar(bar); org.eclipse.swt.widgets.MenuItem fileItem = new org.eclipse.swt.widgets.MenuItem(bar, SWT.CASCADE); fileItem.setText(resources.getString("File_menuitem")); fileItem.setMenu(createFileMenu()); } void createShell(org.eclipse.swt.widgets.Display display) { shell = new org.eclipse.swt.widgets.Shell(display); shell.setText(resources.getString("Window_title")); org.eclipse.swt.layout.GridLayout layout = new org.eclipse.swt.layout.GridLayout(); layout.numColumns = 1; shell.setLayout(layout); shell.addShellListener( new org.eclipse.swt.events.ShellAdapter() { public void shellClosed(org.eclipse.swt.events.ShellEvent e) { lineStyler.disposeColors(); text.removeLineStyleListener(lineStyler); } }); } void createStyledText() { text = new org.eclipse.swt.custom.StyledText( shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); org.eclipse.swt.layout.GridData spec = new org.eclipse.swt.layout.GridData(); spec.horizontalAlignment = GridData.FILL; spec.grabExcessHorizontalSpace = true; spec.verticalAlignment = GridData.FILL; spec.grabExcessVerticalSpace = true; text.setLayoutData(spec); text.addLineStyleListener(lineStyler); text.setEditable(false); org.eclipse.swt.graphics.Color bg = Display.getDefault().getSystemColor(SWT.COLOR_GRAY); text.setBackground(bg); } void displayError(java.lang.String msg) { org.eclipse.swt.widgets.MessageBox box = new org.eclipse.swt.widgets.MessageBox(shell, SWT.ICON_ERROR); box.setMessage(msg); box.open(); } public static void main(java.lang.String[] args) { org.eclipse.swt.widgets.Display display = new org.eclipse.swt.widgets.Display(); org.eclipse.swt.examples.javaviewer.JavaViewer example = new org.eclipse.swt.examples.javaviewer.JavaViewer(); org.eclipse.swt.widgets.Shell shell = example.open(display); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } public org.eclipse.swt.widgets.Shell open(org.eclipse.swt.widgets.Display display) { createShell(display); createMenuBar(); createStyledText(); shell.setSize(500, 400); shell.open(); return shell; } void openFile() { if (fileDialog == null) { fileDialog = new org.eclipse.swt.widgets.FileDialog(shell, SWT.OPEN); } fileDialog.setFilterExtensions(new java.lang.String[] {"*.java", "*.*"}); java.lang.String name = fileDialog.open(); open(name); } void open(java.lang.String name) { final java.lang.String textString; if (name == null || name.length() == 0) { return; } java.io.File file = new java.io.File(name); if (!file.exists()) { java.lang.String message = MessageFormat.format( resources.getString("Err_file_no_exist"), new java.lang.String[] {file.getName()}); displayError(message); return; } try { java.io.FileInputStream stream = new java.io.FileInputStream(file.getPath()); try { java.io.Reader in = new java.io.BufferedReader(new java.io.InputStreamReader(stream)); char[] readBuffer = new char[2048]; java.lang.StringBuffer buffer = new java.lang.StringBuffer((int) file.length()); int n; while ((n = in.read(readBuffer)) > 0) { buffer.append(readBuffer, 0, (-n)); } textString = buffer.toString(); stream.close(); } catch (java.io.IOException e) { java.lang.String message = MessageFormat.format( resources.getString("Err_file_io"), new java.lang.String[] {file.getName()}); displayError(message); return; } } catch (java.io.FileNotFoundException e) { java.lang.String message = MessageFormat.format( resources.getString("Err_not_found"), new java.lang.String[] {file.getName()}); displayError(message); return; } org.eclipse.swt.widgets.Display display = text.getDisplay(); display.asyncExec( new java.lang.Runnable() { public void run() { text.setText(textString); } }); lineStyler.parseBlockComments(textString); } void menuFileExit() { shell.close(); } }
/** * Creates all items located in the popup menu and associates all the menu items with their * appropriate functions. * * @return Menu The created popup menu. */ private Menu createPopUpMenu() { Menu popUpMenu = new Menu(shell, SWT.POP_UP); /** Adds a listener to handle enabling and disabling some items in the Edit submenu. */ popUpMenu.addMenuListener( new MenuAdapter() { @Override public void menuShown(MenuEvent e) { Menu menu = (Menu) e.widget; MenuItem[] items = menu.getItems(); int count = table.getSelectionCount(); items[2].setEnabled(count != 0); // edit items[3].setEnabled(count != 0); // copy items[4].setEnabled(copyBuffer != null); // paste items[5].setEnabled(count != 0); // delete items[7].setEnabled(table.getItemCount() != 0); // find } }); // New MenuItem item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_new")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { newEntry(); } }); new MenuItem(popUpMenu, SWT.SEPARATOR); // Edit item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_edit")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; editEntry(items[0]); } }); // Copy item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_copy")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; copyBuffer = new String[table.getColumnCount()]; for (int i = 0; i < copyBuffer.length; i++) { copyBuffer[i] = items[0].getText(i); } } }); // Paste item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_paste")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (copyBuffer == null) return; TableItem item = new TableItem(table, SWT.NONE); item.setText(copyBuffer); isModified = true; } }); // Delete item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_delete")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length == 0) return; items[0].dispose(); isModified = true; } }); new MenuItem(popUpMenu, SWT.SEPARATOR); // Find... item = new MenuItem(popUpMenu, SWT.PUSH); item.setText(resAddressBook.getString("Pop_up_find")); item.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { searchDialog.open(); } }); return popUpMenu; }
public Shell open(Display display) { // Window dressing - the icon windowIcon = new Image(display, getClass().getClassLoader().getResourceAsStream("icons/joanju.gif")); shell = new Shell(display); shell.setLayout(new FillLayout()); shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { e.doit = closeAddressBook(); } }); shell.setImage(windowIcon); createMenuBar(); searchDialog = new SearchDialog(shell); searchDialog.setSearchAreaNames(columnNames); searchDialog.setSearchAreaLabel(resMessages.getString("Column")); searchDialog.addFindListener( new FindListener() { public boolean find() { return findEntry(); } }); table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); table.setHeaderVisible(true); table.setMenu(createPopUpMenu()); table.addSelectionListener( new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { TableItem[] items = table.getSelection(); if (items.length > 0) launchEditor(items[0]); } }); int[] widths = {150, 50, 200, 200}; for (int i = 0; i < columnNames.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(columnNames[i]); column.setWidth(widths[i]); final int columnIndex = i; column.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { sort(columnIndex); } }); } newAddressBook(); shell.addDisposeListener( new DisposeListener() { public void widgetDisposed(DisposeEvent e) { windowIcon.dispose(); } }); shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300); shell.open(); return shell; }
public class HoverHelp { private static java.util.ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_hoverhelp"); static final int hhiInformation = 0; static final int hhiWarning = 1; static final java.lang.String[] imageLocations = {"information.gif", "warning.gif"}; org.eclipse.swt.graphics.Image[] images; public static void main(java.lang.String[] args) { org.eclipse.swt.widgets.Display display = new org.eclipse.swt.widgets.Display(); org.eclipse.swt.widgets.Shell shell = (new org.eclipse.swt.examples.hoverhelp.HoverHelp()).open(display); while (shell != null && !shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } public org.eclipse.swt.widgets.Shell open(org.eclipse.swt.widgets.Display display) { java.lang.Class clazz = org.eclipse.swt.examples.hoverhelp.HoverHelp.class; try { if (images == null) { images = new org.eclipse.swt.graphics.Image[imageLocations.length]; for (int i = 0; i < imageLocations.length; ++i) { java.io.InputStream stream = clazz.getResourceAsStream(imageLocations[i]); org.eclipse.swt.graphics.ImageData source = new org.eclipse.swt.graphics.ImageData(stream); org.eclipse.swt.graphics.ImageData mask = source.getTransparencyMask(); images[i] = new org.eclipse.swt.graphics.Image(display, source, mask); try { stream.close(); } catch (java.io.IOException e) { e.printStackTrace(); } } } } catch (java.lang.Exception ex) { System.err.println( getResourceString( "error.CouldNotLoadResources", new java.lang.Object[] {ex.getMessage()})); return null; } org.eclipse.swt.widgets.Shell shell = new org.eclipse.swt.widgets.Shell(); createPartControl(shell); shell.addDisposeListener( new org.eclipse.swt.events.DisposeListener() { public void widgetDisposed(org.eclipse.swt.events.DisposeEvent e) { if (images != null) { for (int i = 0; i < images.length; i++) { final org.eclipse.swt.graphics.Image image = images[i]; if (image != null) { image.dispose(); } } images = null; } } }); shell.pack(); shell.open(); return shell; } public java.lang.String getResourceString(java.lang.String key) { try { return resourceBundle.getString(key); } catch (java.util.MissingResourceException e) { return key; } catch (java.lang.NullPointerException e) { return "!" + key + "!"; } } public java.lang.String getResourceString(java.lang.String key, java.lang.Object[] args) { try { return MessageFormat.format(getResourceString(key), args); } catch (java.util.MissingResourceException e) { return key; } catch (java.lang.NullPointerException e) { return "!" + key + "!"; } } public void createPartControl(org.eclipse.swt.widgets.Composite frame) { final org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHandler tooltip = new org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHandler(frame.getShell()); org.eclipse.swt.layout.GridLayout layout = new org.eclipse.swt.layout.GridLayout(); layout.numColumns = 3; frame.setLayout(layout); java.lang.String platform = SWT.getPlatform(); java.lang.String helpKey = "F1"; if (platform.equals("gtk")) { helpKey = "Ctrl+F1"; } if (platform.equals("carbon") || platform.equals("cocoa")) { helpKey = "Help"; } org.eclipse.swt.widgets.ToolBar bar = new org.eclipse.swt.widgets.ToolBar(frame, SWT.BORDER); for (int i = 0; i < 5; i++) { org.eclipse.swt.widgets.ToolItem item = new org.eclipse.swt.widgets.ToolItem(bar, SWT.PUSH); item.setText( getResourceString("ToolItem.text", new java.lang.Object[] {new java.lang.Integer(i)})); item.setData( "TIP_TEXT", getResourceString("ToolItem.tooltip", new java.lang.Object[] {item.getText(), helpKey})); item.setData( "TIP_HELPTEXTHANDLER", new org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHelpTextHandler() { public java.lang.String getHelpText(org.eclipse.swt.widgets.Widget widget) { org.eclipse.swt.widgets.Item item = (org.eclipse.swt.widgets.Item) widget; return getResourceString("ToolItem.help", new java.lang.Object[] {item.getText()}); } }); } org.eclipse.swt.layout.GridData gridData = new org.eclipse.swt.layout.GridData(); gridData.horizontalSpan = 3; bar.setLayoutData(gridData); tooltip.activateHoverHelp(bar); org.eclipse.swt.widgets.Table table = new org.eclipse.swt.widgets.Table(frame, SWT.BORDER); for (int i = 0; i < 4; i++) { org.eclipse.swt.widgets.TableItem item = new org.eclipse.swt.widgets.TableItem(table, SWT.PUSH); item.setText(getResourceString("Item", new java.lang.Object[] {new java.lang.Integer(i)})); item.setData("TIP_IMAGE", images[hhiInformation]); item.setText( getResourceString("TableItem.text", new java.lang.Object[] {new java.lang.Integer(i)})); item.setData( "TIP_TEXT", getResourceString("TableItem.tooltip", new java.lang.Object[] {item.getText(), helpKey})); item.setData( "TIP_HELPTEXTHANDLER", new org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHelpTextHandler() { public java.lang.String getHelpText(org.eclipse.swt.widgets.Widget widget) { org.eclipse.swt.widgets.Item item = (org.eclipse.swt.widgets.Item) widget; return getResourceString("TableItem.help", new java.lang.Object[] {item.getText()}); } }); } table.setLayoutData(new org.eclipse.swt.layout.GridData(GridData.VERTICAL_ALIGN_FILL)); tooltip.activateHoverHelp(table); org.eclipse.swt.widgets.Tree tree = new org.eclipse.swt.widgets.Tree(frame, SWT.BORDER); for (int i = 0; i < 4; i++) { org.eclipse.swt.widgets.TreeItem item = new org.eclipse.swt.widgets.TreeItem(tree, SWT.PUSH); item.setText(getResourceString("Item", new java.lang.Object[] {new java.lang.Integer(i)})); item.setData("TIP_IMAGE", images[hhiWarning]); item.setText( getResourceString("TreeItem.text", new java.lang.Object[] {new java.lang.Integer(i)})); item.setData( "TIP_TEXT", getResourceString("TreeItem.tooltip", new java.lang.Object[] {item.getText(), helpKey})); item.setData( "TIP_HELPTEXTHANDLER", new org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHelpTextHandler() { public java.lang.String getHelpText(org.eclipse.swt.widgets.Widget widget) { org.eclipse.swt.widgets.Item item = (org.eclipse.swt.widgets.Item) widget; return getResourceString("TreeItem.help", new java.lang.Object[] {item.getText()}); } }); } tree.setLayoutData(new org.eclipse.swt.layout.GridData(GridData.VERTICAL_ALIGN_FILL)); tooltip.activateHoverHelp(tree); org.eclipse.swt.widgets.Button button = new org.eclipse.swt.widgets.Button(frame, SWT.PUSH); button.setText(getResourceString("Hello.text")); button.setData("TIP_TEXT", getResourceString("Hello.tooltip")); tooltip.activateHoverHelp(button); } protected static class ToolTipHandler { private org.eclipse.swt.widgets.Shell parentShell; private org.eclipse.swt.widgets.Shell tipShell; private org.eclipse.swt.widgets.Label tipLabelImage; private org.eclipse.swt.widgets.Label tipLabelText; private org.eclipse.swt.widgets.Widget tipWidget; private org.eclipse.swt.graphics.Point tipPosition; public ToolTipHandler(org.eclipse.swt.widgets.Shell parent) { final org.eclipse.swt.widgets.Display display = parent.getDisplay(); this.parentShell = parent; tipShell = new org.eclipse.swt.widgets.Shell(parent, SWT.ON_TOP | SWT.TOOL); org.eclipse.swt.layout.GridLayout gridLayout = new org.eclipse.swt.layout.GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; tipShell.setLayout(gridLayout); tipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); tipLabelImage = new org.eclipse.swt.widgets.Label(tipShell, SWT.NONE); tipLabelImage.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); tipLabelImage.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); tipLabelImage.setLayoutData( new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)); tipLabelText = new org.eclipse.swt.widgets.Label(tipShell, SWT.NONE); tipLabelText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); tipLabelText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); tipLabelText.setLayoutData( new org.eclipse.swt.layout.GridData( (-(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)))); } public void activateHoverHelp(final org.eclipse.swt.widgets.Control control) { control.addMouseListener( new org.eclipse.swt.events.MouseAdapter() { public void mouseDown(org.eclipse.swt.events.MouseEvent e) { if (tipShell.isVisible()) { tipShell.setVisible(false); } } }); control.addMouseTrackListener( new org.eclipse.swt.events.MouseTrackAdapter() { public void mouseExit(org.eclipse.swt.events.MouseEvent e) { if (tipShell.isVisible()) { tipShell.setVisible(false); } tipWidget = null; } public void mouseHover(org.eclipse.swt.events.MouseEvent event) { org.eclipse.swt.graphics.Point pt = new org.eclipse.swt.graphics.Point(event.x, event.y); org.eclipse.swt.widgets.Widget widget = event.widget; if (widget instanceof org.eclipse.swt.widgets.ToolBar) { org.eclipse.swt.widgets.ToolBar w = (org.eclipse.swt.widgets.ToolBar) widget; widget = w.getItem(pt); } if (widget instanceof org.eclipse.swt.widgets.Table) { org.eclipse.swt.widgets.Table w = (org.eclipse.swt.widgets.Table) widget; widget = w.getItem(pt); } if (widget instanceof org.eclipse.swt.widgets.Tree) { org.eclipse.swt.widgets.Tree w = (org.eclipse.swt.widgets.Tree) widget; widget = w.getItem(pt); } if (widget == null) { tipShell.setVisible(false); tipWidget = null; return; } if (widget == tipWidget) { return; } tipWidget = widget; tipPosition = control.toDisplay(pt); java.lang.String text = (java.lang.String) widget.getData("TIP_TEXT"); org.eclipse.swt.graphics.Image image = (org.eclipse.swt.graphics.Image) widget.getData("TIP_IMAGE"); tipLabelText.setText(text != null ? text : ""); tipLabelImage.setImage(image); tipShell.pack(); setHoverLocation(tipShell, tipPosition); tipShell.setVisible(true); } }); control.addHelpListener( new org.eclipse.swt.events.HelpListener() { public void helpRequested(org.eclipse.swt.events.HelpEvent event) { if (tipWidget == null) { return; } org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHelpTextHandler handler = (org.eclipse.swt.examples.hoverhelp.HoverHelp.ToolTipHelpTextHandler) tipWidget.getData("TIP_HELPTEXTHANDLER"); if (handler == null) { return; } java.lang.String text = handler.getHelpText(tipWidget); if (text == null) { return; } if (tipShell.isVisible()) { tipShell.setVisible(false); org.eclipse.swt.widgets.Shell helpShell = new org.eclipse.swt.widgets.Shell(parentShell, SWT.SHELL_TRIM); helpShell.setLayout(new org.eclipse.swt.layout.FillLayout()); org.eclipse.swt.widgets.Label label = new org.eclipse.swt.widgets.Label(helpShell, SWT.NONE); label.setText(text); helpShell.pack(); setHoverLocation(helpShell, tipPosition); helpShell.open(); } } }); } private void setHoverLocation( org.eclipse.swt.widgets.Shell shell, org.eclipse.swt.graphics.Point position) { org.eclipse.swt.graphics.Rectangle displayBounds = shell.getDisplay().getBounds(); org.eclipse.swt.graphics.Rectangle shellBounds = shell.getBounds(); shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0); shellBounds.y = Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0); shell.setBounds(shellBounds); } } protected interface ToolTipHelpTextHandler { public java.lang.String getHelpText(org.eclipse.swt.widgets.Widget widget); } }
public class PaintExample { private static java.util.ResourceBundle resourceBundle = ResourceBundle.getBundle("examples_paint"); private org.eclipse.swt.widgets.Composite mainComposite; private org.eclipse.swt.widgets.Canvas activeForegroundColorCanvas; private org.eclipse.swt.widgets.Canvas activeBackgroundColorCanvas; private org.eclipse.swt.graphics.Color paintColorBlack; private org.eclipse.swt.graphics.Color paintColorWhite; private org.eclipse.swt.graphics.Color[] paintColors; private org.eclipse.swt.graphics.Font paintDefaultFont; private static final int numPaletteRows = 3; private static final int numPaletteCols = 50; private org.eclipse.swt.examples.paint.ToolSettings toolSettings; private org.eclipse.swt.examples.paint.PaintSurface paintSurface; static final int Pencil_tool = 0; static final int Airbrush_tool = 1; static final int Line_tool = 2; static final int PolyLine_tool = 3; static final int Rectangle_tool = 4; static final int RoundedRectangle_tool = 5; static final int Ellipse_tool = 6; static final int Text_tool = 7; static final int None_fill = 8; static final int Outline_fill = 9; static final int Solid_fill = 10; static final int Solid_linestyle = 11; static final int Dash_linestyle = 12; static final int Dot_linestyle = 13; static final int DashDot_linestyle = 14; static final int Font_options = 15; static final int Default_tool = Pencil_tool; static final int Default_fill = None_fill; static final int Default_linestyle = Solid_linestyle; public static final org.eclipse.swt.examples.paint.Tool[] tools = { new org.eclipse.swt.examples.paint.Tool(Pencil_tool, "Pencil", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(Airbrush_tool, "Airbrush", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(Line_tool, "Line", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(PolyLine_tool, "PolyLine", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(Rectangle_tool, "Rectangle", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool( RoundedRectangle_tool, "RoundedRectangle", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(Ellipse_tool, "Ellipse", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool(Text_tool, "Text", "tool", SWT.RADIO), new org.eclipse.swt.examples.paint.Tool( None_fill, "None", "fill", SWT.RADIO, new java.lang.Integer(ToolSettings.ftNone)), new org.eclipse.swt.examples.paint.Tool( Outline_fill, "Outline", "fill", SWT.RADIO, new java.lang.Integer(ToolSettings.ftOutline)), new org.eclipse.swt.examples.paint.Tool( Solid_fill, "Solid", "fill", SWT.RADIO, new java.lang.Integer(ToolSettings.ftSolid)), new org.eclipse.swt.examples.paint.Tool( Solid_linestyle, "Solid", "linestyle", SWT.RADIO, new java.lang.Integer(SWT.LINE_SOLID)), new org.eclipse.swt.examples.paint.Tool( Dash_linestyle, "Dash", "linestyle", SWT.RADIO, new java.lang.Integer(SWT.LINE_DASH)), new org.eclipse.swt.examples.paint.Tool( Dot_linestyle, "Dot", "linestyle", SWT.RADIO, new java.lang.Integer(SWT.LINE_DOT)), new org.eclipse.swt.examples.paint.Tool( DashDot_linestyle, "DashDot", "linestyle", SWT.RADIO, new java.lang.Integer(SWT.LINE_DASHDOT)), new org.eclipse.swt.examples.paint.Tool(Font_options, "Font", "options", SWT.PUSH) }; public PaintExample(org.eclipse.swt.widgets.Composite parent) { mainComposite = parent; initResources(); initActions(); init(); } public static void main(java.lang.String[] args) { org.eclipse.swt.widgets.Display display = new org.eclipse.swt.widgets.Display(); org.eclipse.swt.widgets.Shell shell = new org.eclipse.swt.widgets.Shell(display); shell.setText(getResourceString("window.title")); shell.setLayout(new org.eclipse.swt.layout.GridLayout()); org.eclipse.swt.examples.paint.PaintExample instance = new org.eclipse.swt.examples.paint.PaintExample(shell); instance.createToolBar(shell); org.eclipse.swt.widgets.Composite composite = new org.eclipse.swt.widgets.Composite(shell, SWT.NONE); composite.setLayout(new org.eclipse.swt.layout.FillLayout()); composite.setLayoutData(new org.eclipse.swt.layout.GridData(SWT.FILL, SWT.FILL, true, true)); instance.createGUI(composite); instance.setDefaults(); setShellSize(display, shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } instance.dispose(); } private void createToolBar(org.eclipse.swt.widgets.Composite parent) { org.eclipse.swt.widgets.ToolBar toolbar = new org.eclipse.swt.widgets.ToolBar(parent, SWT.NONE); java.lang.String group = null; for (int i = 0; i < tools.length; i++) { org.eclipse.swt.examples.paint.Tool tool = tools[i]; if (group != null && !tool.group.equals(group)) { new org.eclipse.swt.widgets.ToolItem(toolbar, SWT.SEPARATOR); } group = tool.group; org.eclipse.swt.widgets.ToolItem item = addToolItem(toolbar, tool); if (i == Default_tool || i == Default_fill || i == Default_linestyle) { item.setSelection(true); } } } private org.eclipse.swt.widgets.ToolItem addToolItem( final org.eclipse.swt.widgets.ToolBar toolbar, final org.eclipse.swt.examples.paint.Tool tool) { final java.lang.String id = tool.group + '.' + tool.name; org.eclipse.swt.widgets.ToolItem item = new org.eclipse.swt.widgets.ToolItem(toolbar, tool.type); item.setText(getResourceString(id + ".label")); item.setToolTipText(getResourceString(id + ".tooltip")); item.setImage(tool.image); item.addSelectionListener( new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { tool.action.run(); } }); final int childID = toolbar.indexOf(item); toolbar .getAccessible() .addAccessibleListener( new org.eclipse.swt.accessibility.AccessibleAdapter() { public void getName(org.eclipse.swt.accessibility.AccessibleEvent e) { if (e.childID == childID) { e.result = getResourceString(id + ".description"); } } }); return item; } public void setDefaults() { setPaintTool(Default_tool); setFillType(Default_fill); setLineStyle(Default_linestyle); setForegroundColor(paintColorBlack); setBackgroundColor(paintColorWhite); } public void createGUI(org.eclipse.swt.widgets.Composite parent) { org.eclipse.swt.layout.GridLayout gridLayout; org.eclipse.swt.layout.GridData gridData; org.eclipse.swt.widgets.Composite displayArea = new org.eclipse.swt.widgets.Composite(parent, SWT.NONE); gridLayout = new org.eclipse.swt.layout.GridLayout(); gridLayout.numColumns = 1; displayArea.setLayout(gridLayout); final org.eclipse.swt.widgets.Canvas paintCanvas = new org.eclipse.swt.widgets.Canvas( displayArea, (-(SWT.BORDER | SWT.V_SCROLL)) | SWT.H_SCROLL | SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND); gridData = new org.eclipse.swt.layout.GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); paintCanvas.setLayoutData(gridData); paintCanvas.setBackground(paintColorWhite); final org.eclipse.swt.widgets.Composite colorFrame = new org.eclipse.swt.widgets.Composite(displayArea, SWT.NONE); gridData = new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); colorFrame.setLayoutData(gridData); final org.eclipse.swt.widgets.Composite toolSettingsFrame = new org.eclipse.swt.widgets.Composite(displayArea, SWT.NONE); gridData = new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); toolSettingsFrame.setLayoutData(gridData); final org.eclipse.swt.widgets.Text statusText = new org.eclipse.swt.widgets.Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); gridData = new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); statusText.setLayoutData(gridData); paintSurface = new org.eclipse.swt.examples.paint.PaintSurface(paintCanvas, statusText, paintColorWhite); tools[Pencil_tool].data = new org.eclipse.swt.examples.paint.PencilTool(toolSettings, paintSurface); tools[Airbrush_tool].data = new org.eclipse.swt.examples.paint.AirbrushTool(toolSettings, paintSurface); tools[Line_tool].data = new org.eclipse.swt.examples.paint.LineTool(toolSettings, paintSurface); tools[PolyLine_tool].data = new org.eclipse.swt.examples.paint.PolyLineTool(toolSettings, paintSurface); tools[Rectangle_tool].data = new org.eclipse.swt.examples.paint.RectangleTool(toolSettings, paintSurface); tools[RoundedRectangle_tool].data = new org.eclipse.swt.examples.paint.RoundedRectangleTool(toolSettings, paintSurface); tools[Ellipse_tool].data = new org.eclipse.swt.examples.paint.EllipseTool(toolSettings, paintSurface); tools[Text_tool].data = new org.eclipse.swt.examples.paint.TextTool(toolSettings, paintSurface); gridLayout = new org.eclipse.swt.layout.GridLayout(); gridLayout.numColumns = 3; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; colorFrame.setLayout(gridLayout); activeForegroundColorCanvas = new org.eclipse.swt.widgets.Canvas(colorFrame, SWT.BORDER); gridData = new org.eclipse.swt.layout.GridData(GridData.HORIZONTAL_ALIGN_FILL); gridData.heightHint = 24; gridData.widthHint = 24; activeForegroundColorCanvas.setLayoutData(gridData); activeBackgroundColorCanvas = new org.eclipse.swt.widgets.Canvas(colorFrame, SWT.BORDER); gridData = new org.eclipse.swt.layout.GridData(GridData.HORIZONTAL_ALIGN_FILL); gridData.heightHint = 24; gridData.widthHint = 24; activeBackgroundColorCanvas.setLayoutData(gridData); final org.eclipse.swt.widgets.Canvas paletteCanvas = new org.eclipse.swt.widgets.Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND); gridData = new org.eclipse.swt.layout.GridData(GridData.FILL_HORIZONTAL); gridData.heightHint = 24; paletteCanvas.setLayoutData(gridData); paletteCanvas.addListener( SWT.MouseDown, new org.eclipse.swt.widgets.Listener() { public void handleEvent(org.eclipse.swt.widgets.Event e) { org.eclipse.swt.graphics.Rectangle bounds = paletteCanvas.getClientArea(); org.eclipse.swt.graphics.Color color = getColorAt(bounds, e.x, e.y); if (e.button == 1) { setForegroundColor(color); } else { setBackgroundColor(color); } } private org.eclipse.swt.graphics.Color getColorAt( org.eclipse.swt.graphics.Rectangle bounds, int x, int y) { if (bounds.height <= 1 && bounds.width <= 1) { return paintColorWhite; } final int row = (y - bounds.y) * numPaletteRows / bounds.height; final int col = (x - bounds.x) * numPaletteCols / bounds.width; return paintColors[ Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)]; } }); org.eclipse.swt.widgets.Listener refreshListener = new org.eclipse.swt.widgets.Listener() { public void handleEvent(org.eclipse.swt.widgets.Event e) { if (e.gc == null) { return; } org.eclipse.swt.graphics.Rectangle bounds = paletteCanvas.getClientArea(); for (int row = 0; row < numPaletteRows; ++row) { for (int col = 0; col < numPaletteCols; ++col) { final int x = bounds.width * col / numPaletteCols; final int y = bounds.height * row / numPaletteRows; final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1); final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1); e.gc.setBackground(paintColors[row * numPaletteCols + col]); e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height); } } } }; paletteCanvas.addListener(SWT.Resize, refreshListener); paletteCanvas.addListener(SWT.Paint, refreshListener); gridLayout = new org.eclipse.swt.layout.GridLayout(); gridLayout.numColumns = 4; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; toolSettingsFrame.setLayout(gridLayout); org.eclipse.swt.widgets.Label label = new org.eclipse.swt.widgets.Label(toolSettingsFrame, SWT.NONE); label.setText(getResourceString("settings.AirbrushRadius.text")); final org.eclipse.swt.widgets.Scale airbrushRadiusScale = new org.eclipse.swt.widgets.Scale(toolSettingsFrame, SWT.HORIZONTAL); airbrushRadiusScale.setMinimum(5); airbrushRadiusScale.setMaximum(50); airbrushRadiusScale.setSelection(toolSettings.airbrushRadius); airbrushRadiusScale.setLayoutData( new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL)); airbrushRadiusScale.addSelectionListener( new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { toolSettings.airbrushRadius = airbrushRadiusScale.getSelection(); updateToolSettings(); } }); label = new org.eclipse.swt.widgets.Label(toolSettingsFrame, SWT.NONE); label.setText(getResourceString("settings.AirbrushIntensity.text")); final org.eclipse.swt.widgets.Scale airbrushIntensityScale = new org.eclipse.swt.widgets.Scale(toolSettingsFrame, SWT.HORIZONTAL); airbrushIntensityScale.setMinimum(1); airbrushIntensityScale.setMaximum(100); airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity); airbrushIntensityScale.setLayoutData( new org.eclipse.swt.layout.GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL)); airbrushIntensityScale.addSelectionListener( new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection(); updateToolSettings(); } }); } public void dispose() { if (paintSurface != null) { paintSurface.dispose(); } if (paintColors != null) { for (int i = 0; i < paintColors.length; ++i) { final org.eclipse.swt.graphics.Color color = paintColors[i]; if (color != null) { color.dispose(); } } } paintDefaultFont = null; paintColors = null; paintSurface = null; freeResources(); } public void freeResources() { for (int i = 0; i < tools.length; ++i) { org.eclipse.swt.examples.paint.Tool tool = tools[i]; final org.eclipse.swt.graphics.Image image = tool.image; if (image != null) { image.dispose(); } tool.image = null; } } public org.eclipse.swt.widgets.Display getDisplay() { return mainComposite.getDisplay(); } public static java.lang.String getResourceString(java.lang.String key) { try { return resourceBundle.getString(key); } catch (java.util.MissingResourceException e) { return key; } catch (java.lang.NullPointerException e) { return "!" + key + "!"; } } public static java.lang.String getResourceString(java.lang.String key, java.lang.Object[] args) { try { return MessageFormat.format(getResourceString(key), args); } catch (java.util.MissingResourceException e) { return key; } catch (java.lang.NullPointerException e) { return "!" + key + "!"; } } private void init() { org.eclipse.swt.widgets.Display display = mainComposite.getDisplay(); paintColorWhite = new org.eclipse.swt.graphics.Color(display, 255, 255, 255); paintColorBlack = new org.eclipse.swt.graphics.Color(display, 0, 0, 0); paintDefaultFont = display.getSystemFont(); paintColors = new org.eclipse.swt.graphics.Color[numPaletteCols * numPaletteRows]; paintColors[0] = paintColorBlack; paintColors[1] = paintColorWhite; for (int i = 2; i < paintColors.length; i++) { paintColors[i] = new org.eclipse.swt.graphics.Color(display, i * 7 % 255, i * 23 % 255, i * 51 % 255); } toolSettings = new org.eclipse.swt.examples.paint.ToolSettings(); toolSettings.commonForegroundColor = paintColorBlack; toolSettings.commonBackgroundColor = paintColorWhite; toolSettings.commonFont = paintDefaultFont; } private void initActions() { for (int i = 0; i < tools.length; ++i) { final org.eclipse.swt.examples.paint.Tool tool = tools[i]; java.lang.String group = tool.group; if (group.equals("tool")) { tool.action = new java.lang.Runnable() { public void run() { setPaintTool(tool.id); } }; } else { if (group.equals("fill")) { tool.action = new java.lang.Runnable() { public void run() { setFillType(tool.id); } }; } else { if (group.equals("linestyle")) { tool.action = new java.lang.Runnable() { public void run() { setLineStyle(tool.id); } }; } else { if (group.equals("options")) { tool.action = new java.lang.Runnable() { public void run() { org.eclipse.swt.widgets.FontDialog fontDialog = new org.eclipse.swt.widgets.FontDialog( paintSurface.getShell(), SWT.PRIMARY_MODAL); org.eclipse.swt.graphics.FontData[] fontDatum = toolSettings.commonFont.getFontData(); if (fontDatum != null && fontDatum.length > 0) { fontDialog.setFontList(fontDatum); } fontDialog.setText(getResourceString("options.Font.dialog.title")); paintSurface.hideRubberband(); org.eclipse.swt.graphics.FontData fontData = fontDialog.open(); paintSurface.showRubberband(); if (fontData != null) { try { org.eclipse.swt.graphics.Font font = new org.eclipse.swt.graphics.Font( mainComposite.getDisplay(), fontData); toolSettings.commonFont = font; updateToolSettings(); } catch (org.eclipse.swt.SWTException ex) { } } } }; } } } } } } public void initResources() { final java.lang.Class clazz = org.eclipse.swt.examples.paint.PaintExample.class; if (resourceBundle != null) { try { for (int i = 0; i < tools.length; ++i) { org.eclipse.swt.examples.paint.Tool tool = tools[i]; java.lang.String id = tool.group + '.' + tool.name; java.io.InputStream sourceStream = clazz.getResourceAsStream(getResourceString(id + ".image")); org.eclipse.swt.graphics.ImageData source = new org.eclipse.swt.graphics.ImageData(sourceStream); org.eclipse.swt.graphics.ImageData mask = source.getTransparencyMask(); tool.image = new org.eclipse.swt.graphics.Image(null, source, mask); try { sourceStream.close(); } catch (java.io.IOException e) { e.printStackTrace(); } } return; } catch (java.lang.Throwable t) { } } java.lang.String error = resourceBundle != null ? getResourceString("error.CouldNotLoadResources") : "Unable to load resources"; freeResources(); throw new java.lang.RuntimeException(error); } public void setFocus() { mainComposite.setFocus(); } public void setForegroundColor(org.eclipse.swt.graphics.Color color) { if (activeForegroundColorCanvas != null) { activeForegroundColorCanvas.setBackground(color); } toolSettings.commonForegroundColor = color; updateToolSettings(); } public void setBackgroundColor(org.eclipse.swt.graphics.Color color) { if (activeBackgroundColorCanvas != null) { activeBackgroundColorCanvas.setBackground(color); } toolSettings.commonBackgroundColor = color; updateToolSettings(); } public void setPaintTool(int id) { org.eclipse.swt.examples.paint.PaintTool paintTool = (org.eclipse.swt.examples.paint.PaintTool) tools[id].data; paintSurface.setPaintSession(paintTool); updateToolSettings(); } public void setFillType(int id) { java.lang.Integer fillType = (java.lang.Integer) tools[id].data; toolSettings.commonFillType = fillType.intValue(); updateToolSettings(); } public void setLineStyle(int id) { java.lang.Integer lineType = (java.lang.Integer) tools[id].data; toolSettings.commonLineStyle = lineType.intValue(); updateToolSettings(); } private static void setShellSize( org.eclipse.swt.widgets.Display display, org.eclipse.swt.widgets.Shell shell) { org.eclipse.swt.graphics.Rectangle bounds = display.getBounds(); org.eclipse.swt.graphics.Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); if (size.x > bounds.width) { size.x = bounds.width * 9 / 10; } if (size.y > bounds.height) { size.y = bounds.height * 9 / 10; } shell.setSize(size); } private void updateToolSettings() { final org.eclipse.swt.examples.paint.PaintTool activePaintTool = paintSurface.getPaintTool(); if (activePaintTool == null) { return; } activePaintTool.endSession(); activePaintTool.set(toolSettings); activePaintTool.beginSession(); } }