advertisement

Article:
  Adding a Preferences Window to Your Application
Subject:   Java Version - Solution
Date:   2002-06-02 18:55:49
From:   jsumnertx
As with the other examples, here's my java solution.


1) One thing that got me in this one is that you can (and need to have) awakeFromNib(). Previously, I was doing all of the work in the object constructor but I moved it to awakFromNib so there would be access to the preference panel checkbox objects.
2) Interestingly, in order for awakeFromNib to be called, the controller must inherit from NSObject, not Object. So, I had to change things to use Object (btw, you can do a copy and paste of a class in Interface Builder.. That helped)


So, here's the new code.


/* Controller */


import com.apple.cocoa.foundation.*;
import com.apple.cocoa.application.*;


public class Controller extends NSObject {


NSTextField emailField; /* IBOutlet */
NSTextField firstNameField; /* IBOutlet */
NSTextField lastNameField; /* IBOutlet */
NSTextField homePhoneField; /* IBOutlet */
NSTextField mobilePhoneField; /* IBOutlet */
NSTextField workPhoneField; /* IBOutlet */


NSButton emailCB;
NSButton firstNameCB;
NSButton lastNameCB;
NSButton homePhoneCB;
NSButton mobilePhoneCB;
NSButton workPhoneCB;



NSTableView tableView; /* IBOutlet */
NSMutableArray records;
NSUserDefaults prefs;

NSMutableDictionary tableColumns;

NSDictionary checkBoxes;

String recordsFile;
String kIdentifierArray[]={"First Name", "Last Name", "Email", "Home Phone", "Work Phone", "Mobile Phone"}; // NOT null-terminated. Uses java Strings


NSMutableArray userColumns;

// Controller()
void awakeFromNib()
{

prefs = NSUserDefaults.standardUserDefaults();
tableColumns = new NSMutableDictionary();


recordsFile = "~/Library/Preferences/AddressBookData.plist";
recordsFile = NSPathUtilities.stringByExpandingTildeInPath(recordsFile);

java.io.File rf=new java.io.File(recordsFile);
if (prefs.arrayForKey("Address")!=null)
records = new NSMutableArray(prefs.arrayForKey("Address"));
else if (rf.exists()==true)
records = new NSMutableArray(readFileIntoArray(recordsFile));
else
records = new NSMutableArray();


// NSArray identifiers=new NSArray(kIdentifierArray);



NSBundle bundle=NSBundle.mainBundle();
String path=bundle.pathForResource("Identifiers","plist");
NSArray identifiers=readFileIntoArray(path);
String identarray[]=new String[identifiers.count()];
identifiers.getObjects(identarray);

NSButton kButtonArray[]={firstNameCB, lastNameCB, emailCB, homePhoneCB, workPhoneCB, mobilePhoneCB};
checkBoxes=new NSDictionary(kButtonArray, identarray);


this.addInitialColumnsForIdentifiers(identifiers);


if (prefs.arrayForKey("User Columns") !=null){
userColumns = new NSMutableArray(prefs.arrayForKey("User Columns"));
this.initializeTableWithColumns(userColumns);
}
else {
userColumns=new NSMutableArray();
firstNameCB.setState(NSCell.OnState);
lastNameCB.setState(NSCell.OnState);
emailCB.setState(NSCell.OnState);
homePhoneCB.setState(NSCell.OnState);
}



}

NSArray readFileIntoArray(String path)
{
NSArray loadedRecords=null;
try{
java.io.File file = new java.io.File(path);
NSData data = new NSData(file);
loadedRecords = (NSArray)NSPropertyListSerialization.propertyListFromXMLData(data);
}
catch (Exception e)
{
loadedRecords=null;
}
return loadedRecords;
}


public void initializeTableWithColumns(NSArray identifiers)
{
NSTableColumn column;
String identifier;

java.util.Enumeration e=tableView.tableColumns().objectEnumerator();
while ((column=(NSTableColumn)e.nextElement())!=null){
tableView.removeTableColumn(column);
}

e=identifiers.objectEnumerator();
while ((identifier=(String)e.nextElement())!=null){
column=(NSTableColumn)tableColumns.objectForKey(identifier);
tableView.addTableColumn(column);
NSButton button=(NSButton)checkBoxes.objectForKey(identifier);
button.setState(NSCell.OnState);
}
}

public void addInitialColumnForIdentifier(String identifier)
{
NSTableColumn newColumn;
newColumn = new NSTableColumn();
newColumn.setIdentifier(identifier);
newColumn.headerCell().setStringValue(identifier);
newColumn.headerCell().setAlignment(NSText.CenterTextAlignment);
newColumn.headerCell().setEditable(true);
tableColumns.setObjectForKey(newColumn, identifier);
}

public void addInitialColumnsForIdentifiers(NSArray identifiers)
{
// uses java enumerator
java.util.Enumeration e=identifiers.objectEnumerator();
String identifier;

while ((identifier=(String)e.nextElement())!=null){
this.addInitialColumnForIdentifier(identifier);
}
}

public NSDictionary createRecord()
{
NSMutableDictionary record = new NSMutableDictionary();

record.setObjectForKey(firstNameField.stringValue(), "First Name");
record.setObjectForKey(lastNameField.stringValue(), "Last Name");
record.setObjectForKey(emailField.stringValue(), "Email");
record.setObjectForKey(homePhoneField.stringValue(), "Home Phone");
record.setObjectForKey(workPhoneField.stringValue(), "Work Phone");
record.setObjectForKey(mobilePhoneField.stringValue(), "Mobile Phone");

firstNameField.setStringValue("");
lastNameField.setStringValue("");
emailField.setStringValue("");
homePhoneField.setStringValue("");
workPhoneField.setStringValue("");
mobilePhoneField.setStringValue("");

return record;
}


public void addRecord(Object sender) { /* IBAction */
records.addObject(createRecord());
tableView.reloadData();
saveData(records);
}


public void setColumn(NSButton sender) {
String identifier=sender.title();
NSTableColumn column=(NSTableColumn)tableColumns.objectForKey(identifier);

if (sender.state()==NSCell.OnState){
tableView.addTableColumn(column);
saveTableColumnPrefs();
}
else if (sender.state()==NSCell.OffState){
tableView.removeTableColumn(column);
saveTableColumnPrefs();
}
}

public void deleteRecord(Object sender) { /* IBAction */

if (tableView.numberOfSelectedRows() == 0)
return;
NSApplication.beep();
int status = NSAlertPanel.runAlert("Warning!", "Are you sure you want to delete the selected record(s)?", "OK", "Cancel", null);


if ( status == NSAlertPanel.DefaultReturn ) {
NSMutableArray tempArray = new NSMutableArray();
NSEnumerator enumerator = tableView.selectedRowEnumerator();
Integer item;
item = (Integer)enumerator.nextElement();
while ( item != null ) {
tempArray.addObject(records.objectAtIndex(item.intValue()));
item = (Integer)enumerator.nextElement();
}
records.removeObjectsInArray(tempArray);
tableView.reloadData();
saveData(records);
}
}


public void insertRecord(Object sender) { /* IBAction */
int index = tableView.selectedRow();
if (index >= 0)
records.insertObjectAtIndex(createRecord(), index);
else
records.addObject(createRecord());
tableView.reloadData();
saveData(records);
}

public int numberOfRowsInTableView(NSTableView aTableView){
// I had to add this check because this method was getting
// called before awakeFromNib for some reason
if (records!=null)
return records.count();
else
return 0;
}

public Object tableViewObjectValueForLocation( NSTableView aTableView, NSTableColumn aTableColumn, int rowIndex){
NSDictionary theRecord;
Object theValue=null;

theRecord = (NSDictionary)records.objectAtIndex(rowIndex);
if (theRecord!=null)
theValue = theRecord.objectForKey(aTableColumn.identifier());
return theValue;
}



private void saveData(NSArray records)
{
this.saveArrayToFile(records, recordsFile);
prefs.setObjectForKey(records, "Address");
prefs.synchronize();
}


private void saveArrayToFile(NSArray array, String filename)
{
try
{
java.net.URL fileURL=NSPathUtilities.URLWithPath(filename);
NSData data = NSPropertyListSerialization.XMLDataFromPropertyList(array);
data.writeToURL(fileURL, true);
}
catch (Exception e)
{
// put up a dialog
int status = NSAlertPanel.runAlert("Warning!", "Unable to save data", "OK", null, null);
}
}

private void saveTableColumnPrefs()
{
NSTableColumn column;
java.util.Enumeration e=tableView.tableColumns().objectEnumerator();

userColumns.removeAllObjects();
while ((column=(NSTableColumn)e.nextElement())!=null)
{
userColumns.addObject(column.identifier());
}
prefs.setObjectForKey(userColumns,"User Columns");
}
}



1 to 1 of 1
  1. Java Version - Solution
    2003-08-30 15:46:48  anonymous2 [View]

    • Java Version - Solution
      2004-01-01 01:56:57  anonymous2 [View]

1 to 1 of 1