The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Help me with this implementing TableModule

Posted by sam_hou on November 23, 2001 at 5:02 PM

I encounter a servere problem when I run a swing project.

The structure is:
ongoing
|->todoswing(main)
|->todoitem(
|->todolist
|->todorepository

Here are the codes of this project, when I tried to add a row into the
table, the application downed, who can tell me why? I tried to debug this
file, I found I created the row successfully, but it maybe something wrong
with the "fireTableRowsInserted(0, 0);" in the method of insertRow() in the
class of todotablemodel.


//todorepository.java
package ongoing.toDoStorage;

import ongoing.toDoComponents.*;
import java.util.Iterator;

public interface ToDoRepository {

boolean add( ToDoItem newItem );

boolean remove( ToDoItem itemToRemove );

ToDoItem find( String nameToFind );

Iterator iterator();
}

//todoitem.java
package ongoing.toDoComponents;

import java.util.GregorianCalendar;
import java.util.Calendar;

public class ToDoItem {

protected String name = null;
protected String description = null;
protected GregorianCalendar creationDate = null;
protected GregorianCalendar dueDate = null;

// START constructors -----------------------------

public ToDoItem() {
this( "", "", null );

}

public ToDoItem( String newName, String newDescription, GregorianCalendar
newDueDate ) {
name = newName;
description = newDescription;
dueDate = newDueDate;

creationDate = new GregorianCalendar();
}

// END constructors -----------------------------

// START ACCESSOR methods -----------------------------

public void setName( String newName ) {
name = newName;
}

public String getName() {
return name;
}

public void setDescription( String newDescription ) {
description = newDescription;
}

public String getDescription() {
return description;
}

public Calendar getCreationDate() {
return creationDate;
}

public void setDueDate( GregorianCalendar newDueDate ) {
dueDate = newDueDate;
}

public Calendar getDueDate() {
return dueDate;
}

// END ACCESSOR methods ------------------------------

public String toDebugString() {

return "ToDoItem: " + name + ", " + description
+ ", Created on " + creationDate.getTime()
+ ", Due Date is " + dueDate.getTime();

}

public String toString() {

return name;
}
}

//todolist.java
package ongoing.toDoStorage;

import ongoing.toDoComponents.*;
import java.util.Iterator;
import java.util.Vector;

public class ToDoList implements ToDoRepository {

private Vector theList = null;

// nothing to do in constructor, so no need to include default constructor

public boolean add( ToDoItem newItem ) {
return getTheList().add( newItem );
}

public boolean remove( ToDoItem itemToRemove ) {
return getTheList().remove( itemToRemove );

}

public ToDoItem find( String nameToFind ) {
try {

// Iterate through "theList", compare name of each with "nameToFind",
// return first matching ToDoItem
for (Iterator i = getTheList().iterator(); i.hasNext(); ) {

ToDoItem nextItem = (ToDoItem) i.next();
if ( nextItem.getName().equals( nameToFind ) ) {
return nextItem;
}

}
} catch (Throwable e) {
handleException(e);
}

// No match found, or exception caught before finding match,
// so return null
return null;
}

public Iterator iterator() {
return getTheList().iterator();
}

private Vector getTheList() {

if ( theList == null ) {
try {
theList = new Vector();
} catch (Throwable e) {
handleException(e);
}
}

return theList;
}

private void handleException(Throwable e) {
System.out.println("Error in ToDoList: " + e.getMessage() );
e.printStackTrace();
}


}

//todoswing.java
package ongoing.toDoSwing;

import java.awt.BorderLayout;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

import java.text.SimpleDateFormat;

import javax.swing.ListSelectionModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.table.AbstractTableModel;

import ongoing.toDoComponents.ToDoItem;

import ongoing.toDoStorage.ToDoRepository;
import ongoing.toDoStorage.ToDoList;

/**
* ToDoSwing uses JTable to produce a Swing front-end for the
* ToDoList class. ToDoItems can be added, deleted, and editted.
*/
public class ToDoSwing extends JFrame {
public static void main(String[] args) {
ToDoSwing todo = new ToDoSwing();
todo.show();
}

private JPanel tablePane;
private JPanel buttonPane;

private JTable toDoTable;
private ToDoTableModel toDoModel;

private JButton insertRow;
private JButton deleteRow;

/**
* Constructor creates the ToDoSwing window
*/
public ToDoSwing() {
super("To-do List");

tablePane = new JPanel();
buttonPane = new JPanel();

/*
* Create the data model for the JTable
*/
toDoModel = new ToDoTableModel();

/*
* Create the JTable to display to-do items
*/
toDoTable = new JTable(toDoModel);

/*
* Only allow one row to be selected at a time
*/
toDoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

/*
* Put the JTable into a JScrollPane to support automatic
* scrolling.
*/
JScrollPane scrollPane = new JScrollPane(toDoTable);
tablePane.add(scrollPane);


/*
* Insert Row button allows an item to be added
* to the end of the list of to-do items
*/
insertRow = new JButton("Insert Row");
insertRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
toDoModel.insertRow();
}
});


/*
* Delete Selected Row allows the selected item
* to be removed from the list of to-do items
* If no row is selected when the button is pressed,
* an error message dialog pops up.
*/
deleteRow = new JButton("Delete Selected Row");
deleteRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int selectedRow = toDoTable.getSelectedRow();
if (selectedRow == -1) {
JOptionPane.showMessageDialog(
ToDoSwing.this,
"Please select a row to delete",
"Deletion Error",
JOptionPane.ERROR_MESSAGE);
return;
}

toDoModel.deleteRow(selectedRow);
}
});


/*
* Add the insert and delete buttons to the
* button pane
*/
buttonPane.add(insertRow);
buttonPane.add(deleteRow);

/*
* Add the JTable to the middle of the frame and
* the buttons to the bottom of the frame (centered)
*/
getContentPane().add(tablePane, BorderLayout.CENTER);
getContentPane().add(buttonPane, BorderLayout.SOUTH);


/*
* When the user exits the application, simply shut down
* the program. If you want to supply an 'Are you sure?'
* dialog window when the user tries to close the application
* down, this is the place to do it.
*/
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});

pack();
}
}

/**
* This class uses ToDoList to store a list of to-do items
*/
class ToDoTableModel extends AbstractTableModel {
/*
* data represents the items in the to-do list
*/
private ToDoList data = new ToDoList();


/**
* The fields associated with items in the
* to-do list. If new attributes are
* added to ToDoItem, this code will also
* need to be updated to support these new fields
*/
private String[] fields = new String[] {
"Name",
"Description",
"Creation Date",
"Due Date"
};

/*************** TableModel interface methods implemented below ********/

/**
* Return the number of fields.
*/
public int getColumnCount() {
//fill in the code for this method!
return fields.length;
}

/**
* This method returns the name of a column associated with
* a particular index. Note that the model gives you
* the index associated with the original position of
* a column in the table even if the user manually drags it
* to a new position.
*/
public String getColumnName(int column) {
//replace existing code and fill in the code for this method!
return fields[column];
}

/**
* Returns the number of rown in the list of To-Do items.
* Since ToDoList does not have a method like 'size()',
* it is necessary to iterate through all the records and keep
* count of how many are found in total. This is not ideal,
* but it will do for now.
*/
public int getRowCount() {
//replace existing code and fill in the code for this method!
int rown=0;
while(data.iterator().hasNext()){
rown++;
data.iterator().next();
}
return rown;
}

/**
* Return the object in the cell of the table
* specified by the row and column index that's
* passed in. First iterate through the
* items in the the to-do list until you
* reach the item at the specified row,
* then use getColumnByName to get the
* attribute for the specified column
* of the desired item. Determine if
* the object is a Calendar using the
* 'instanceof' operator and use the
* following code to format date
* information for display:
* Date date = ((Calendar) obj).getTime();
*
* return new SimpleDateFormat("MM/dd/yyyy").format(date);
*
*/
public Object getValueAt(int row, int column) {
//replace existing code and fill in the code for this method!
Object obj;
obj=getColumnByName(fields[column],getItem(row));
if(column<2)
return obj;
else
{
Date date=((GregorianCalendar) obj).getTime();
return new SimpleDateFormat("MM/dd/yyyy").format(date);
}
}

/**
* When an item is editted, this method puts the changed
* item back into the ToDoList. Find the appropriate
* item as in the getValueAt method, then use
* the setColumnByName method to store the value
* in the selected cell in ToDoList. See
* fireTableCellUpdated method to make sure
* the change is properly displayed by the table.
*/
public void setValueAt(Object newVal, int row, int column) {
//replace existing code and fill in the code for this method!
getValueAt(row,column);
String column_name=getColumnName(column);
setColumnByName(column_name,getItem(row),newVal);
fireTableCellUpdated(row, column);
}

/**
* The item create date should not be editable,
* all other cells should be editable.
*/
public boolean isCellEditable(int row, int column) {
//replace existing code and fill in the code for this method!
if(column!=2)
return true;
else
return false;
}

/*************** Utility methods below ********/

/**
* Append a new, blank, row to the list of
* items in ToDoList
*/
public void insertRow() {
//replace existing code and fill in the code for this method!
ToDoItem new_Item=new ToDoItem();
data.add(new_Item);
for(int i=0;i<4&&i!=2;i++)
setColumnByName(fields,new_Item,"");
fireTableRowsInserted(0, 0);
}

/**
* Find the item located in the specified row
* and remove it from ToDoList. See
* fireTableDataChanged method to refresh the
* display of the table.
*/
public void deleteRow(int row) {
//replace existing code and fill in the code for this method!
data.remove(getItem(row));
fireTableRowsDeleted(row, row);
}

/**
* For a given ToDoItem, return the object
* in the item associated with the specified
* column name.
*/
private Object getColumnByName(String columnName, ToDoItem item) {
if (columnName.equals("Name")) {
return item.getName();
}

if (columnName.equals("Description")) {
return item.getDescription();
}

if (columnName.equals("Creation Date")) {
return item.getCreationDate();
}

if (columnName.equals("Due Date")) {
return item.getDueDate();
}

return null;
}

/**
* Set the object for the specified column name in the
* DoToItem that is passed in to the new value
* specified by newVal. The date must be entered in
* MM/dd/yyyy (e.g. 12/04/2001) format.
*/
private void setColumnByName(String columnName, ToDoItem item,
Object newVal) {
if (columnName.equals("Name")) {
item.setName((String) newVal);
}

if (columnName.equals("Description")) {
item.setDescription((String) newVal);
}

if (columnName.equals("Due Date")) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dateFormat.setLenient(true);
try {
Date date = dateFormat.parse((String) newVal);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

item.setDueDate((GregorianCalendar) calendar);
}
catch (Exception e) {
/*
* For now just ignore an eror that occurs due
* to a bad date format being passed in
*/
e.printStackTrace();
}
}
}

/**
* Return the ToDoItem associated with a particular row
*/
private ToDoItem getItem(int row) {
int i=0;
Iterator iter = data.iterator();

ToDoItem item = null;
while (iter.hasNext()) {
item = (ToDoItem) iter.next();
if (i == row) {
break;
}

i++;
}

return item;
}
}






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us