Java/Design Pattern/Mediator Pattern
Версия от 18:01, 31 мая 2010; (обсуждение)
Design Patterns By Example in Java- Mediator Pattern
/*
Software Architecture Design Patterns in Java
by Partha Kuchana
Auerbach Publications
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
public class MediatorPatternFTPGUI extends JFrame {
public static final String newline = "\n";
public static final String UPLOAD = "Upload";
public static final String DOWNLOAD = "Download";
public static final String DELETE = "Delete";
public static final String EXIT = "Exit";
private JPanel pnlFTPUI;
private LocalList localList;
private RemoteList remoteList;
private DefaultListModel defLocalList, defRemoteList;
private Mediator mdtr = new Mediator();
public MediatorPatternFTPGUI() throws Exception {
super("Design Patterns By Example - Mediator Pattern ");
// Create controls
defLocalList = new DefaultListModel();
defRemoteList = new DefaultListModel();
localList = new LocalList(defLocalList, mdtr);
remoteList = new RemoteList(defRemoteList, mdtr);
pnlFTPUI = new JPanel();
localList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
localList.setSelectedIndex(-1);
JScrollPane spLocalList = new JScrollPane(localList);
remoteList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
remoteList.setSelectedIndex(-1);
JScrollPane spRemoteList = new JScrollPane(remoteList);
//Create Labels
JLabel lblLocalList = new JLabel("Local List:");
JLabel lblRemoteList = new JLabel("Remote List:");
JLabel lblSpacer = new JLabel(" ");
//Create buttons
UploadButton btnUpload = new UploadButton(MediatorPatternFTPGUI.UPLOAD,
mdtr);
btnUpload.setMnemonic(KeyEvent.VK_U);
DownloadButton btnDownload = new DownloadButton(
MediatorPatternFTPGUI.DOWNLOAD, mdtr);
btnDownload.setMnemonic(KeyEvent.VK_N);
DeleteButton btnDelete = new DeleteButton(MediatorPatternFTPGUI.DELETE,
mdtr);
btnDelete.setMnemonic(KeyEvent.VK_D);
JButton btnExit = new JButton(MediatorPatternFTPGUI.EXIT);
btnExit.setMnemonic(KeyEvent.VK_X);
buttonHandler vf = new buttonHandler();
listHandler lh = new listHandler();
btnUpload.addActionListener(vf);
btnDownload.addActionListener(vf);
btnDelete.addActionListener(vf);
btnExit.addActionListener(vf);
localList.addListSelectionListener(lh);
remoteList.addListSelectionListener(lh);
JPanel lstPanel = new JPanel();
GridBagLayout gridbag2 = new GridBagLayout();
lstPanel.setLayout(gridbag2);
GridBagConstraints gbc2 = new GridBagConstraints();
lstPanel.add(lblLocalList);
lstPanel.add(lblRemoteList);
lstPanel.add(spLocalList);
lstPanel.add(spRemoteList);
lstPanel.add(lblSpacer);
gbc2.gridx = 0;
gbc2.gridy = 0;
gridbag2.setConstraints(lblLocalList, gbc2);
gbc2.gridx = 1;
gbc2.gridy = 0;
gridbag2.setConstraints(lblSpacer, gbc2);
gbc2.gridx = 5;
gbc2.gridy = 0;
gridbag2.setConstraints(lblRemoteList, gbc2);
gbc2.gridx = 0;
gbc2.gridy = 1;
gridbag2.setConstraints(spLocalList, gbc2);
gbc2.gridx = 5;
gbc2.gridy = 1;
gridbag2.setConstraints(spRemoteList, gbc2);
//-----------------------------------
//For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel();
//----------------------------------------------
GridBagLayout gridbag = new GridBagLayout();
buttonPanel.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
buttonPanel.add(lstPanel);
buttonPanel.add(btnUpload);
buttonPanel.add(btnDownload);
buttonPanel.add(btnDelete);
buttonPanel.add(btnExit);
gbc.insets.top = 5;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 1;
gbc.gridy = 0;
gridbag.setConstraints(btnUpload, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
gridbag.setConstraints(btnDownload, gbc);
gbc.gridx = 3;
gbc.gridy = 0;
gridbag.setConstraints(btnDelete, gbc);
gbc.gridx = 4;
gbc.gridy = 0;
gridbag.setConstraints(btnExit, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gridbag.setConstraints(lstPanel, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.insets.left = 2;
gbc.insets.right = 2;
gbc.insets.top = 40;
//****************************************************
//Add the buttons and the log to the frame
Container contentPane = getContentPane();
contentPane.add(lstPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
btnUpload.setEnabled(false);
btnDelete.setEnabled(false);
btnDownload.setEnabled(false);
initialize();
try {
UIManager.setLookAndFeel(new WindowsLookAndFeel());
SwingUtilities.updateComponentTreeUI(MediatorPatternFTPGUI.this);
} catch (Exception ex) {
System.out.println(ex);
}
}
private void initialize() {
// fill some test data here into the listbox.
defLocalList.addElement("first.html");
defLocalList.addElement("second.html");
defLocalList.addElement("third.html");
defLocalList.addElement("fourth.html");
defLocalList.addElement("fifth.html");
defLocalList.addElement("Design Patterns.html");
defRemoteList.addElement("sixth.html");
defRemoteList.addElement("seventh.html");
defRemoteList.addElement("eighth.html");
defRemoteList.addElement("ninth.html");
defRemoteList.addElement("Design Patterns By Ex.html");
}
public static void main(String[] args) throws Exception {
JFrame frame = new MediatorPatternFTPGUI();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//frame.pack();
frame.setSize(450, 300);
frame.setVisible(true);
}
class listHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
CommandInterface CommandObj = (CommandInterface) e.getSource();
CommandObj.processEvent();
}
}
class buttonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(MediatorPatternFTPGUI.EXIT)) {
System.exit(1);
}
CommandInterface CommandObj = (CommandInterface) e.getSource();
CommandObj.processEvent();
}
public buttonHandler() {
}
}
interface CommandInterface {
public void processEvent();
}
class UploadButton extends JButton implements CommandInterface {
Mediator mdtr;
public void processEvent() {
mdtr.UploadItem();
}
public UploadButton(String name, Mediator inp_mdtr) {
super(name);
mdtr = inp_mdtr;
mdtr.registerUploadButton(this);
}
}
class DownloadButton extends JButton implements CommandInterface {
Mediator mdtr;
public void processEvent() {
mdtr.DownloadItem();
}
public DownloadButton(String name, Mediator inp_mdtr) {
super(name);
mdtr = inp_mdtr;
mdtr.registerDownloadButton(this);
}
}
class DeleteButton extends JButton implements CommandInterface {
Mediator mdtr;
public void processEvent() {
mdtr.DeleteItem();
}
public DeleteButton(String name, Mediator inp_mdtr) {
super(name);
mdtr = inp_mdtr;
mdtr.registerDeleteButton(this);
}
}
class LocalList extends JList implements CommandInterface {
Mediator mdtr;
public void processEvent() {
mdtr.LocalListSelect();
}
public LocalList(DefaultListModel defObj, Mediator inp_mdtr) {
super(defObj);
mdtr = inp_mdtr;
mdtr.registerLocalList(this);
}
}
class RemoteList extends JList implements CommandInterface {
Mediator mdtr;
public void processEvent() {
mdtr.RemoteListSelect();
}
public RemoteList(DefaultListModel defObj, Mediator inp_mdtr) {
super(defObj);
mdtr = inp_mdtr;
mdtr.registerRemoteList(this);
}
}
class Mediator {
private UploadButton btnUpload;
private DownloadButton btnDownload;
private DeleteButton btnDelete;
private LocalList localList;
private RemoteList remoteList;
public void registerUploadButton(UploadButton inp_ib) {
btnUpload = inp_ib;
}
public void registerDownloadButton(DownloadButton inp_dnb) {
btnDownload = inp_dnb;
}
public void registerDeleteButton(DeleteButton inp_db) {
btnDelete = inp_db;
}
public void registerLocalList(LocalList inp_arl) {
localList = inp_arl;
}
public void registerRemoteList(RemoteList inp_drl) {
remoteList = inp_drl;
}
public void UploadItem() {
int index = localList.getSelectedIndex();
String selectedItem = localList.getSelectedValue().toString();
((DefaultListModel) localList.getModel()).remove(index);
((DefaultListModel) remoteList.getModel()).addElement(selectedItem);
btnUpload.setEnabled(false);
btnDelete.setEnabled(false);
btnDownload.setEnabled(false);
}
public void DownloadItem() {
int index = remoteList.getSelectedIndex();
String selectedItem = remoteList.getSelectedValue().toString();
((DefaultListModel) remoteList.getModel()).remove(index);
((DefaultListModel) localList.getModel()).addElement(selectedItem);
btnUpload.setEnabled(false);
btnDelete.setEnabled(false);
btnDownload.setEnabled(false);
}
public void DeleteItem() {
int index = localList.getSelectedIndex();
if (index >= 0) {
((DefaultListModel) localList.getModel()).remove(index);
}
index = remoteList.getSelectedIndex();
if (index >= 0) {
((DefaultListModel) remoteList.getModel()).remove(index);
}
btnUpload.setEnabled(false);
btnDelete.setEnabled(false);
btnDownload.setEnabled(false);
}
public void LocalListSelect() {
remoteList.setSelectedIndex(-1);
btnUpload.setEnabled(true);
btnDelete.setEnabled(true);
btnDownload.setEnabled(false);
}
public void RemoteListSelect() {
localList.setSelectedIndex(-1);
btnUpload.setEnabled(false);
btnDelete.setEnabled(true);
btnDownload.setEnabled(true);
}
}
}// end of class
Mediator Pattern 2
//[C] 2002 Sun Microsystems, Inc.---
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RunMediatorPattern {
public static void main(String [] arguments){
System.out.println("Example for the Mediator pattern");
System.out.println("In this demonstration, the ContactMediatorImpl class will");
System.out.println(" coordinate updates between three controls in a GUI - the");
System.out.println(" ContactDisplayPanel, the ContactEditorPanel, and the");
System.out.println(" ContactSelectorPanel. As its name suggests, the Mediator");
System.out.println(" mediates the activity between the elements of the GUI,");
System.out.println(" translating method calls from one panel into the appropriate");
System.out.println(" method calls on the other GUI components.");
Contact contact = new ContactImpl("", "", "", "");
Contact contact1 = new ContactImpl("Duke", "", "Java Advocate", "The Patterns Guild");
ContactMediatorImpl mediator = new ContactMediatorImpl();
mediator.addContact(contact);
mediator.addContact(contact1);
MediatorGui gui = new MediatorGui();
gui.setContactMediator(mediator);
gui.createGui();
}
}
class ContactEditorPanel extends JPanel implements ActionListener{
private ContactMediator mediator;
private JTextField firstName, lastName, title, organization;
private JButton create, update;
public ContactEditorPanel(){
createGui();
}
public ContactEditorPanel(ContactMediator newMediator){
setContactMediator(newMediator);
createGui();
}
public void createGui(){
setLayout(new BorderLayout());
JPanel editor = new JPanel();
editor.setLayout(new GridLayout(4, 2));
editor.add(new JLabel("First Name:"));
firstName = new JTextField(20);
editor.add(firstName);
editor.add(new JLabel("Last Name:"));
lastName = new JTextField(20);
editor.add(lastName);
editor.add(new JLabel("Title:"));
title = new JTextField(20);
editor.add(title);
editor.add(new JLabel("Organization:"));
organization = new JTextField(20);
editor.add(organization);
add(editor, BorderLayout.CENTER);
JPanel control = new JPanel();
create = new JButton("Create Contact");
update = new JButton("Update Contact");
create.addActionListener(this);
update.addActionListener(this);
control.add(create);
control.add(update);
add(control, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == create){
createContact();
}
else if (source == update){
updateContact();
}
}
public void createContact(){
mediator.createContact(firstName.getText(), lastName.getText(),
title.getText(), organization.getText());
}
public void updateContact(){
mediator.updateContact(firstName.getText(), lastName.getText(),
title.getText(), organization.getText());
}
public void setContactFields(Contact contact){
firstName.setText(contact.getFirstName());
lastName.setText(contact.getLastName());
title.setText(contact.getTitle());
organization.setText(contact.getOrganization());
}
public void setContactMediator(ContactMediator newMediator){
mediator = newMediator;
}
}
class ContactMediatorImpl implements ContactMediator{
private ContactDisplayPanel display;
private ContactEditorPanel editor;
private ContactSelectorPanel selector;
private ArrayList contacts = new ArrayList();
private int contactIndex;
public void setContactDisplayPanel(ContactDisplayPanel displayPanel){
display = displayPanel;
}
public void setContactEditorPanel(ContactEditorPanel editorPanel){
editor = editorPanel;
}
public void setContactSelectorPanel(ContactSelectorPanel selectorPanel){
selector = selectorPanel;
}
public void createContact(String firstName, String lastName, String title, String organization){
Contact newContact = new ContactImpl(firstName, lastName, title, organization);
addContact(newContact);
selector.addContact(newContact);
display.contactChanged(newContact);
}
public void updateContact(String firstName, String lastName, String title, String organization){
Contact updateContact = (Contact)contacts.get(contactIndex);
if (updateContact != null){
updateContact.setFirstName(firstName);
updateContact.setLastName(lastName);
updateContact.setTitle(title);
updateContact.setOrganization(organization);
display.contactChanged(updateContact);
}
}
public void selectContact(Contact contact){
if (contacts.contains(contact)){
contactIndex = contacts.indexOf(contact);
display.contactChanged(contact);
editor.setContactFields(contact);
}
}
public Contact [] getAllContacts(){
return (Contact [])contacts.toArray(new Contact[1]);
}
public void addContact(Contact contact){
if (!contacts.contains(contact)){
contacts.add(contact);
}
}
}
class ContactDisplayPanel extends JPanel{
private ContactMediator mediator;
private JTextArea displayRegion;
public ContactDisplayPanel(){
createGui();
}
public ContactDisplayPanel(ContactMediator newMediator){
setContactMediator(newMediator);
createGui();
}
public void createGui(){
setLayout(new BorderLayout());
displayRegion = new JTextArea(10, 40);
displayRegion.setEditable(false);
add(new JScrollPane(displayRegion));
}
public void contactChanged(Contact contact){
displayRegion.setText(
"Contact\n\tName: " + contact.getFirstName() +
" " + contact.getLastName() + "\n\tTitle: " +
contact.getTitle() + "\n\tOrganization: " +
contact.getOrganization());
}
public void setContactMediator(ContactMediator newMediator){
mediator = newMediator;
}
}
class ContactSelectorPanel extends JPanel implements ActionListener{
private ContactMediator mediator;
private JComboBox selector;
public ContactSelectorPanel(){
createGui();
}
public ContactSelectorPanel(ContactMediator newMediator){
setContactMediator(newMediator);
createGui();
}
public void createGui(){
selector = new JComboBox(mediator.getAllContacts());
selector.addActionListener(this);
add(selector);
}
public void actionPerformed(ActionEvent evt){
mediator.selectContact((Contact)selector.getSelectedItem());
}
public void addContact(Contact contact){
selector.addItem(contact);
selector.setSelectedItem(contact);
}
public void setContactMediator(ContactMediator newMediator){
mediator = newMediator;
}
}
class MediatorGui{
private ContactMediator mediator;
public void setContactMediator(ContactMediator newMediator){ mediator = newMediator; }
public void createGui(){
JFrame mainFrame = new JFrame("Mediator example");
Container content = mainFrame.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
ContactSelectorPanel select = new ContactSelectorPanel(mediator);
ContactDisplayPanel display = new ContactDisplayPanel(mediator);
ContactEditorPanel edit = new ContactEditorPanel(mediator);
content.add(select);
content.add(display);
content.add(edit);
mediator.setContactSelectorPanel(select);
mediator.setContactDisplayPanel(display);
mediator.setContactEditorPanel(edit);
mainFrame.addWindowListener(new WindowCloseManager());
mainFrame.pack();
mainFrame.setVisible(true);
}
private class WindowCloseManager extends WindowAdapter{
public void windowClosing(WindowEvent evt){
System.exit(0);
}
}
}
interface ContactMediator{
public void setContactDisplayPanel(ContactDisplayPanel displayPanel);
public void setContactEditorPanel(ContactEditorPanel editorPanel);
public void setContactSelectorPanel(ContactSelectorPanel selectorPanel);
public void createContact(String firstName, String lastName, String title, String organization);
public void updateContact(String firstName, String lastName, String title, String organization);
public Contact [] getAllContacts();
public void selectContact(Contact contact);
}
interface Contact extends Serializable{
public static final String SPACE = " ";
public String getFirstName();
public String getLastName();
public String getTitle();
public String getOrganization();
public void setFirstName(String newFirstName);
public void setLastName(String newLastName);
public void setTitle(String newTitle);
public void setOrganization(String newOrganization);
}
class ContactImpl implements Contact{
private String firstName;
private String lastName;
private String title;
private String organization;
public ContactImpl(){}
public ContactImpl(String newFirstName, String newLastName,
String newTitle, String newOrganization){
firstName = newFirstName;
lastName = newLastName;
title = newTitle;
organization = newOrganization;
}
public String getFirstName(){ return firstName; }
public String getLastName(){ return lastName; }
public String getTitle(){ return title; }
public String getOrganization(){ return organization; }
public void setFirstName(String newFirstName){ firstName = newFirstName; }
public void setLastName(String newLastName){ lastName = newLastName; }
public void setTitle(String newTitle){ title = newTitle; }
public void setOrganization(String newOrganization){ organization = newOrganization; }
public String toString(){
return firstName + SPACE + lastName;
}
}
Mediator pattern in Java
/*
The Design Patterns Java Companion
Copyright (C) 1998, by James W. Cooper
IBM Thomas J. Watson Research Center
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
//-
public class MedDemo extends JFrame implements ActionListener {
KidList kidList;
PickedKidsList picked;
KTextField tx;
MoveButton Move;
ClearButton Clear;
Mediator med;
public MedDemo() {
super("Mediator demo");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Mediator med = new Mediator();
JPanel jp = new JPanel();
getContentPane().add(jp);
jp.setLayout(new BorderLayout());
JPanel center = new JPanel();
JPanel left = new JPanel();
JPanel right = new JPanel();
jp.add("Center", center);
center.setLayout(new GridLayout(1, 2));
center.add(left);
center.add(right);
left.setBorder(new EmptyBorder(5, 5, 5, 5));
right.setBorder(new EmptyBorder(5, 5, 5, 5));
kidList = new KidList(med);
left.setLayout(new BorderLayout());
left.add("Center", kidList);
right.setLayout(new BorderLayout());
tx = new KTextField(med);
Move = new MoveButton(this, med);
Clear = new ClearButton(this, med);
JPanel rtop = new JPanel();
jp.add("North", rtop);
rtop.add(tx);
rtop.add(Move);
rtop.add(Clear);
picked = new PickedKidsList(med);
right.add("Center", picked);
med.init();
setSize(new Dimension(400, 300));
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Command comd = (Command) e.getSource();
comd.Execute();
}
static public void main(String argv[]) {
new MedDemo();
}
}
class Kid {
String frname, lname, club;
int age;
float time;
public Kid(String line) {
StringTokenizer tok = new StringTokenizer(line);
String lnum = tok.nextToken();
frname = tok.nextToken();
lname = tok.nextToken();
age = new Integer(tok.nextToken()).intValue();
club = tok.nextToken();
time = new Float(tok.nextToken()).floatValue();
}
//-
public Object getData(int key) {
switch (key) {
case ParseVar.FRNAME:
return frname;
case ParseVar.LNAME:
return lname;
case ParseVar.CLUB:
return club;
case ParseVar.AGE:
return new Integer(age);
case ParseVar.TIME:
return new Float(time);
}
return null;
}
//
public int getAge() {
return age;
}
public float getTime() {
return time;
}
public String getFrname() {
return frname;
}
public String getLname() {
return lname;
}
public String getClub() {
return club;
}
}
class PickedKidsList extends JawtList {
Mediator med;
public PickedKidsList(Mediator md) {
super(20);
med = md;
med.registerPicked(this);
}
}
class KidList extends JawtList implements ListSelectionListener {
KidData kdata;
Mediator med;
public KidList(Mediator md) {
super(20);
kdata = new KidData("50free.txt");
fillKidList();
med = md;
med.registerKidList(this);
addListSelectionListener(this);
}
//
public void valueChanged(ListSelectionEvent ls) {
JList obj = (JList) ls.getSource();
if (obj.getSelectedIndex() >= 0)
med.select();
}
//
private void fillKidList() {
Enumeration ekid = kdata.elements();
while (ekid.hasMoreElements()) {
Kid k = (Kid) ekid.nextElement();
add(k.getFrname() + " " + k.getLname());
}
}
}
//this is a simple adapter class to
//convert List awt methods to Swing methods
class JawtList extends JScrollPane implements ListSelectionListener, awtList {
private JList listWindow;
private JListData listContents;
public JawtList(int rows) {
listContents = new JListData();
listWindow = new JList(listContents);
listWindow.setPrototypeCellValue("Abcdefg Hijkmnop");
getViewport().add(listWindow);
}
public void addListSelectionListener(ListSelectionListener iList) {
listWindow.addListSelectionListener(iList);
}
public void add(String s) {
listContents.addElement(s);
}
public void remove(String s) {
listContents.removeElement(s);
}
public void clear() {
listContents.clear();
}
public String[] getSelectedItems() {
Object[] obj = listWindow.getSelectedValues();
String[] s = new String[obj.length];
for (int i = 0; i < obj.length; i++)
s[i] = obj[i].toString();
return s;
}
public void clearSelection() {
listWindow.clearSelection();
}
public Object getSelectedValue() {
return listWindow.getSelectedValue();
}
public void valueChanged(ListSelectionEvent e) {
}
}
class JListData extends AbstractListModel {
private Vector data;
public JListData() {
data = new Vector();
}
public int getSize() {
return data.size();
}
public Object getElementAt(int index) {
return data.elementAt(index);
}
public void addElement(String s) {
data.addElement(s);
fireIntervalAdded(this, data.size() - 1, data.size());
}
public void removeElement(String s) {
data.removeElement(s);
fireIntervalRemoved(this, 0, data.size());
}
public void clear() {
int size = data.size();
data = new Vector();
fireIntervalRemoved(this, 0, size);
}
}
interface awtList {
public void add(String s);
public void remove(String s);
public String[] getSelectedItems();
}
class Mediator {
private ClearButton clearButton;
private MoveButton moveButton;
private KTextField ktext;
private KidList klist;
private PickedKidsList picked;
public Mediator() {
}
public void Move() {
picked.add(ktext.getText());
clearButton.setEnabled(true);
}
public void init() {
Clear();
}
public void Clear() {
ktext.setText("");
moveButton.setEnabled(false);
clearButton.setEnabled(false);
picked.clear();
klist.clearSelection();
System.out.println("cleared");
}
public void select() {
String s = (String) klist.getSelectedValue();
ktext.setText(s);
moveButton.setEnabled(true);
System.out.println("selected");
}
public void registerClear(ClearButton cb) {
clearButton = cb;
}
public void registerMove(MoveButton mv) {
moveButton = mv;
}
public void registerText(KTextField tx) {
ktext = tx;
}
public void registerPicked(PickedKidsList pl) {
picked = pl;
}
public void registerKidList(KidList kl) {
klist = kl;
}
}
class MoveButton extends JButton implements Command {
Mediator med; //copy of the Mediator
public MoveButton(ActionListener fr, Mediator md) {
super("Copy"); //create the button
addActionListener(fr); //add its listener
med = md; //copy in the Mediator instance
med.registerMove(this); //register with the Mediator
}
public void Execute() { //execute the copy
med.Move();
}
}
class ClearButton extends JButton implements Command {
Mediator med;
public ClearButton(ActionListener act, Mediator md) {
super("Clear");
addActionListener(act);
med = md;
med.registerClear(this);
}
public void Execute() {
med.Clear();
}
}
interface Command {
public void Execute();
}
class KTextField extends JTextField {
Mediator med;
public KTextField(Mediator md) {
super(10);
med = md;
med.registerText(this);
}
}
class ParseObject {
public static final int VERB = 1000, VAR = 1010, MULTVAR = 1020;
protected int value;
protected int type;
public int getValue() {
return value;
}
public int getType() {
return type;
}
}
class ParseVar extends ParseObject {
static final int FRNAME = 0, LNAME = 1, AGE = 2, CLUB = 3, TIME = 4,
tabMAX = 5;
public ParseVar(String s) {
s = s.toLowerCase();
value = -1;
type = VAR;
if (s.equals("frname"))
value = FRNAME;
if (s.equals("lname"))
value = LNAME;
if (s.equals("age"))
value = AGE;
if (s.equals("club"))
value = CLUB;
if (s.equals("time"))
value = TIME;
}
public boolean isLegal() {
return (value >= 0);
}
}
class InputFile {
RandomAccessFile f = null;
boolean errflag;
String s = null;
public InputFile(String fname) {
errflag = false;
try {
//open file
f = new RandomAccessFile(fname, "r");
} catch (IOException e) {
//print error if not found
System.out.println("no file found");
errflag = true; //and set flag
}
}
public boolean checkErr() {
return errflag;
}
public String read() {
//read a single field up to a comma or end of line
String ret = "";
if (s == null) //if no data in string
{
s = readLine(); //read next line
}
if (s != null) //if there is data
{
s.trim(); //trim off blanks
int i = s.indexOf(","); //find next comma
if (i <= 0) {
ret = s.trim(); //if no commas go to end of line
s = null; //and null out stored string
} else {
ret = s.substring(0, i).trim(); //return left of comma
s = s.substring(i + 1); //save right of comma
}
} else
ret = null;
return ret; //return string
}
public String readLine() {
//read in a line from the file
s = null;
try {
s = f.readLine(); //could throw error
} catch (IOException e) {
errflag = true;
System.out.println("File read error");
}
return s;
}
public void close() {
try {
f.close(); //close file
} catch (IOException e) {
System.out.println("File close error");
errflag = true;
}
}
}
class KidData {
Vector kids;
public KidData(String filename) {
kids = new Vector();
InputFile f = new InputFile(filename);
String s = f.readLine();
while (s != null) {
if (s.trim().length() > 0) {
Kid k = new Kid(s);
kids.addElement(k);
}
s = f.readLine();
}
}
//
public Kid[] getData() {
Kid[] kd = new Kid[kids.size()];
for (int i = 0; i < kids.size(); i++)
kd[i] = (Kid) kids.elementAt(i);
return kd;
}
//
public Enumeration elements() {
return kids.elements();
}
//-
public Enumeration kidsInClub(String club) {
return new kidClub(this, club);
}
//
public int size() {
return kids.size();
}
//
public Kid getKid(int i) {
return (Kid) kids.elementAt(i);
}
//
public Vector getKidData(int key) {
Vector v = new Vector();
for (int i = 0; i < kids.size(); i++)
v.addElement(getKid(i).getData(key));
return v;
}
//
public int getTableKey(String tabName) {
int key = -1;
tabName = tabName.toLowerCase();
if (tabName.equals("frname"))
key = ParseVar.FRNAME;
if (tabName.equals("lname"))
key = ParseVar.LNAME;
if (tabName.equals("age"))
key = ParseVar.AGE;
if (tabName.equals("club"))
key = ParseVar.CLUB;
if (tabName.equals("time"))
key = ParseVar.TIME;
return key;
}
//
public String getTableName(int i) {
String name = "";
switch (i) {
case ParseVar.FRNAME:
name = "frname";
case ParseVar.LNAME:
name = "lname";
case ParseVar.AGE:
name = "age";
case ParseVar.CLUB:
name = "club";
case ParseVar.TIME:
name = "time";
}
return name;
}
//
}
class kidClub implements Enumeration {
String clubMask;
int index;
Kid kid;
Enumeration ke;
KidData kdata;
public kidClub(KidData kd, String club) {
clubMask = club;
kdata = kd;
index = 0;
kid = null;
ke = kdata.elements();
}
public boolean hasMoreElements() {
boolean found = false;
while (ke.hasMoreElements() && !found) {
kid = (Kid) ke.nextElement();
found = kid.getClub().equals(clubMask);
}
if (!found)
kid = null;
return found;
}
public Object nextElement() {
if (kid != null)
return kid;
else
throw new NoSuchElementException();
}
}
//50free.txt
/*
1 Amanda McCarthy 12 WCA 29.28
2 Jamie Falco 12 HNHS 29.80
3 Meaghan O"Donnell 12 EDST 30.00
4 Greer Gibbs 12 CDEV 30.04
5 Rhiannon Jeffrey 11 WYW 30.04
6 Sophie Connolly 12 WAC 30.05
7 Dana Helyer 12 ARAC 30.18
8 Lindsay Marotto 12 OAK 30.23
9 Sarah Treichel 12 WYW 30.35
10 Ashley McEntee 12 RAC 30.47
11 Rachel Brookman 12 CAT 30.51
12 Michelle Ducharme 12 LEHY 30.51
13 Karleen Danais 12 NES 30.70
14 Megan Loock 12 WAC 30.90
15 Kaitlyn Ament 12 HNHS 30.93
16 Tara Schoen 12 WYW 31.01
17 Kate Olshefski 12 NCY 31.01
18 Emma Zuidema 12 HMST 31.07
19 Katie Persing 12 OAK 31.14
20 Christina Monsees 11 RAC 31.27
21 Kimberly Watcke 12 CDEV 31.50
22 Colleen Smith 12 AJSC 31.52
23 Chloe Osborne 12 GYWD 31.74
24 Natalia Fugate 12 WAC 31.75
25 Lisa McHale 11 RAC 31.76
26 Lindsay Cowles 11 NES 31.79
27 Jacquelyn Yavarone 12 HNHS 31.83
28 Molly Fenn 12 WRAT 31.84
29 Karin Brudvig 12 HMST 31.84
30 Annie Duffy 12 MGAT 31.90
31 Nicole Coia 11 WCA 31.94
32 Elizabeth Rice 12 WYW 31.96
33 Yvette Landwehr 12 WRAT 32.00
34 Ashley Recklet 12 SHEL 32.24
35 Lauren McKenna 11 PSDY 32.27
36 Kristen Fontaine 12 EDST 32.28
37 Diana Cooke 12 ZEUS 32.33
38 Kimberly Gambino 11 NES 32.43
39 Jenny Morgan 11 NES 32.49
40 Colleen Coelho 12 CDEV 32.50
41 Leigh Gordon 12 CDEV 32.62
42 Caitlin Gillen 12 WYW 32.75
43 Kristen Skroski 12 HNHS 32.91
44 Sarah Greenberg 11 CDEV 32.97
45 Kathy Collins 12 EHBB 33.11
46 Morgan Bullock 12 ICSC 33.33
47 Brittany Medlin 12 CAT 33.33
48 Haley Ottenbreit 12 HNHS 33.35
49 Laura Kunces 11 WAC 33.64
50 Hayley Wolfgruber 12 WYW 33.73
51 Katie Duffy 12 MGAT 34.24
*/