swtaddressbook.java
来自「java的swt图形程序」· Java 代码 · 共 1,335 行 · 第 1/3 页
JAVA
1,335 行
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ResourceBundle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
/**
* 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 SWTAddressBook {
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 = {
"Last_name","First_name",
"Business_phone","Home_phone",
"Email", "Fax" };
public static void main(String[] args) {
Display display = new Display();
SWTAddressBook application = new SWTAddressBook();
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() {
public void shellClosed(ShellEvent e) {
e.doit = closeAddressBook();
}
});
createMenuBar();
searchDialog = new SearchDialog(shell);
searchDialog.setSearchAreaNames(columnNames);
searchDialog.setSearchAreaLabel("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)
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() {
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("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 = new Cursor(shell.getDisplay(), 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);
if (waitCursor != null)
waitCursor.dispose();
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("Title_bar"
+ "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[] {
"Book_filter_name" + " (*.adr)",
"All_filter_name" + " (*.*)" });
String name = fileDialog.open();
if (name == null)
return;
File file = new File(name);
if (!file.exists()) {
displayError("File" + file.getName()
+ " " + "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("File_not_found" + "\n"
+ file.getName());
return;
} catch (IOException e) {
displayError("IO_error_read" + "\n"
+ file.getName());
return;
} finally {
shell.setCursor(null);
waitCursor.dispose();
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
displayError("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("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("File_not_found" + "\n"
+ file.getName());
return false;
} catch (IOException e) {
displayError("IO_error_write" + "\n"
+ file.getName());
return false;
} finally {
shell.setCursor(null);
waitCursor.dispose();
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
displayError("IO_error_close"
+ "\n" + file.getName());
return false;
}
}
}
shell.setText("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)",
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?