im lost and cant figure it out..i will post my four files if anyone wants to take a look..thanks so much.
files include : contact.java,prog2.java,persistantstorage.java,jcu stomtable.java
Expand|Select|Wrap|Line Numbers
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.border.*;
- import javax.swing.table.*;
- import java.util.*;
- public class prog2 extends JFrame {
- private JPanel mainPanel;
- Box horizontalbox;
- private JLabel sname;
- private JTextField [] fields;
- private JButton submit, clear,sub;
- private PersistentStorage ps;
- private JFrame parentReference;
- private JLabel statusLabel;
- private JCustomTable dataTable;
- private JTable table;
- private String cardShowing;
- private JFrame frame = this;
- private String name,name1,name2,name3,name4,name5,name6,name7,name8,name9;
- public prog2() {
- fields = new JTextField[Contact.NUM_FIELDS];
- ps = new PersistentStorage();
- parentReference = this;
- statusLabel = new JLabel();
- setWindowAttributes();
- setLookAndFeel();
- addMainPanel();
- addComponents();
- setVisible(true);
- }
- //////////////////////////////////////////////////////////////////////////////
- /// MAIN METHODS ///
- //////////////////////////////////////////////////////////////////////////////
- private void setWindowAttributes() {
- setTitle("Personal Contact Manager");
- setSize(900,450);
- setLocation(50,50);
- setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- }
- private void setLookAndFeel() {
- try {
- UIManager.setLookAndFeel(
- UIManager.getSystemLookAndFeelClassName());
- //UIManager.getCrossPlatformLookAndFeelClassName());
- }
- catch(Exception e) {
- System.out.println("Sorry, LookAndFeel not found. Available LAFs are\n");
- UIManager.LookAndFeelInfo [] x = UIManager.getInstalledLookAndFeels();
- for(int i=0; i < x.length; i++)
- System.out.println(x[i]);
- }
- }
- private void addMainPanel() {
- mainPanel = new JPanel();
- mainPanel.setLayout(new FlowLayout());
- mainPanel.setBackground(new Color(240,240,240));
- add(mainPanel);
- }
- private void make(){
- }
- private void addComponents() {
- Box name = Box.createHorizontalBox();
- //this is code for drop down menu.
- //String[] dropDown = { "Friends", "Family", "School", "Work", "Church" };
- //JComboBox dropDownMenu = new JComboBox(dropDown);
- //code below is for name boxes.
- JLabel first = new JLabel("First: ");
- JLabel last = new JLabel("Last: ");
- JLabel nick = new JLabel("Group: ");
- //JTextField textFieldfname = new JTextField("", 7);
- fields[Contact.F_NAME]= new JTextField(7);
- //JTextField textFieldlname = new JTextField("", 7);
- fields[Contact.L_NAME]= new JTextField(7);
- //JTextField textFieldnickname = new JTextField("", 7);
- fields[Contact.GROUP]= new JTextField(7);
- name.setPreferredSize(new Dimension (850,60));
- name.setMaximumSize(new Dimension (850,60));
- name.add(first);
- //name.add(textFieldfname);
- name.add(fields[Contact.F_NAME]);
- name.add(Box.createRigidArea(new Dimension(5,0)));
- name.add(last);
- //name.add(textFieldlname);
- name.add(fields[Contact.L_NAME]);
- name.add(Box.createRigidArea(new Dimension(5,0)));
- name.add(nick);
- //name.add(textFieldnickname);
- name.add(fields[Contact.GROUP]);
- name.add(Box.createRigidArea(new Dimension(5,0)));
- //name.add(dropDownMenu);
- name.add(Box.createRigidArea(new Dimension(5,0)));
- name.setBorder(BorderFactory.createTitledBorder("Contact Info"));
- mainPanel.add(name);
- mainPanel.add(Box.createRigidArea(new Dimension(1000,10)));
- //creating tabbed pane
- JTabbedPane ContactPane = new JTabbedPane();
- JPanel contactPanel = new JPanel();
- JPanel listPanel= new JPanel();
- listPanel.setLayout(new BorderLayout());
- ContactPane.setPreferredSize(new Dimension (875,325));
- ContactPane.setMaximumSize(new Dimension(875,325));
- Box Contacts = Box.createHorizontalBox();
- ContactPane.addTab("Contact Info",contactPanel);
- ContactPane.addTab("View Contacts", makeViewTable());
- //ContactPane.addTab("Contact List",listPanel);
- Contacts.add(ContactPane);
- mainPanel.add(Contacts);
- mainPanel.add(Box.createRigidArea(new Dimension(1000,0)));
- cardShowing = "View Contacts";
- //ContactPane.addMouseListener(new MyMouseListener());
- //adding contact info to tabbed pane
- JLabel Address = new JLabel("Address: ");
- fields[Contact.ADDRESS] = new JTextField(15);
- JLabel City = new JLabel("City: ");
- fields[Contact.CITY] = new JTextField(10);
- JLabel State = new JLabel("State: ");
- fields[Contact.STATE] = new JTextField(5);
- JLabel Zip = new JLabel("Zip: ");
- fields[Contact.ZIP] = new JTextField(5);
- JLabel Email = new JLabel("Primary Email: ");
- fields[Contact.PRIMARY_EMAIL] = new JTextField(18);
- JLabel Email2 = new JLabel("Secondary Email: ");
- fields[Contact.SECONDARY_EMAIL] = new JTextField(18);
- sname = new JLabel("ScreenName:");
- fields[Contact.SCREEN_NAME] = new JTextField(10);
- JLabel Phone1 = new JLabel("Primary Phone:");
- fields[Contact.PRIMARY_PHONE] = new JTextField(10);
- JLabel Phone2 = new JLabel("Secondary Phone: ");
- fields[Contact.SECONDARY_PHONE] = new JTextField(10);
- contactPanel.add(Box.createRigidArea(new Dimension(0,8)));
- contactPanel.add(Address);
- contactPanel.add(fields[Contact.ADDRESS]);
- contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
- contactPanel.add(City);
- contactPanel.add(fields[Contact.CITY]);
- contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
- contactPanel.add(State);
- contactPanel.add(fields[Contact.STATE]);
- contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
- contactPanel.add(Zip);
- contactPanel.add(fields[Contact.ZIP]);
- contactPanel.add(Box.createRigidArea(new Dimension(1000,15)));
- contactPanel.add(Email);
- contactPanel.add(fields[Contact.PRIMARY_EMAIL]);
- contactPanel.add(Box.createRigidArea(new Dimension(30,0)));
- contactPanel.add(Email2);
- contactPanel.add(fields[Contact.SECONDARY_EMAIL]);
- contactPanel.add(Box.createRigidArea(new Dimension(1000,15)));
- contactPanel.add(sname);
- contactPanel.add(fields[Contact.SCREEN_NAME]);
- contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
- contactPanel.add(Phone1);
- contactPanel.add(fields[Contact.PRIMARY_PHONE]);
- contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
- contactPanel.add(Phone2);
- contactPanel.add(fields[Contact.SECONDARY_PHONE]);
- contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
- //contactPanel.addMouseListener(new MyMouseListener());
- //comment field
- JLabel comments = new JLabel("Comments: ");
- //JTextArea commentField = new JTextArea(5,30);
- fields[Contact.PRIMARY_COMMENTS] = new JTextField(30);
- //commentField.setLineWrap(true);
- //commentField.setBorder(new LineBorder(Color.black,1));
- contactPanel.add(comments);
- //contactPanel.add(commentField);
- contactPanel.add(fields[Contact.PRIMARY_COMMENTS]);
- contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
- //submit and clear buttons
- Box buttonPane=Box.createHorizontalBox();
- submit = new JButton("Submit");
- clear = new JButton("Clear");
- //submit.addActionListener(new SubmitHandler());
- //submit.setMaximumSize(new Dimension(40,40));
- buttonPane.createHorizontalGlue();
- submit.addActionListener(new SubmitHandler());
- buttonPane.add(submit);
- buttonPane.createHorizontalGlue();
- clear.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- for(int i=0; i < Contact.NUM_FIELDS; i++)
- fields[i].setText("");
- statusLabel.setText("");
- }
- });
- buttonPane.add(clear);
- buttonPane.createHorizontalGlue();
- contactPanel.add(buttonPane);
- contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
- contactPanel.add(statusLabel);
- }
- //////////////////////////////////////////////////////////////////////////////
- /// GUI BUILD AND PLACE
- //////////////////////////////////////////////////////////////////////////////
- class SubmitHandler implements ActionListener {
- public void actionPerformed(ActionEvent e)
- {
- if(fields[0].getText().trim().length() == 0 ||
- fields[1].getText().trim().length() == 0 ||
- fields[2].getText().trim().length() == 0) {
- statusLabel.setText("Incomplete Record, not saved.");
- return;
- }
- Vector<String> tmp = new Vector<String>(Contact.NUM_FIELDS);
- for(int i=0; i < Contact.NUM_FIELDS; i++)
- tmp.add(fields[i].getText());
- Contact c = new Contact(tmp);
- if(ps.insert(c.getKey(),c)) {
- Object [] newData = new Object[fields.length];
- for(int i=0; i < fields.length; i++)
- newData[i] = fields[i].getText().trim();
- dataTable.insertRow(newData);
- for(int i=0; i < Contact.NUM_FIELDS; i++)
- fields[i].setText("");
- statusLabel.setText("Record saved");
- }
- else {
- statusLabel.setText("");
- JOptionPane.showMessageDialog(parentReference, "Sorry, duplicate entry.",
- "Error",JOptionPane.ERROR_MESSAGE);
- }
- }
- }
- //////////////////////////////////////////////////////////////////////////////
- /// HELPER METHODS ///
- //////////////////////////////////////////////////////////////////////////////
- private JPanel makeViewTable() {
- JPanel panel = new JPanel();
- JPanel listPanel= new JPanel();
- panel.setLayout(new BorderLayout());
- Vector<String> columnNames = new Vector<String>(Contact.NUM_FIELDS);
- columnNames.add("First Name");
- columnNames.add("Last Name");
- columnNames.add("Group");
- //columnNames.add("Address");
- //columnNames.add("City");
- //columnNames.add("State");
- //columnNames.add("Zip");
- //columnNames.add("Email 2");
- columnNames.add("Phone 1");
- columnNames.add("Email 1");
- columnNames.add("ScreenName");
- //columnNames.add("Phone 2");
- //columnNames.add("Comments");
- Vector<Vector<String>> fieldData = new Vector<Vector<String>>(Contact.NUM_FIELDS);
- Iterator<Contact> iter = ps.values();
- while(iter.hasNext()) {
- Contact tmp = iter.next();
- Vector<String> tmpV = tmp.getValueVector();
- fieldData.add(tmpV);
- }
- dataTable = new JCustomTable(fieldData, columnNames);
- dataTable.setTableHeaderBackground(new Color(255,200,200));
- dataTable.setFont(new Font("Arial",Font.BOLD, 14));
- dataTable.setCustomRowColors(Color.white, new Color(220,220,255));
- dataTable.setColumnsSortable(new Color(220,220,255));
- //dataTable.setPreferredSize(new Dimension(400,400));
- //dataTable.setMaximumSize(new Dimension (400,400));
- JScrollPane scrollPane = new JScrollPane(dataTable);
- panel.add(scrollPane, BorderLayout.CENTER);
- panel.addMouseListener(new MyMouseListener());
- Box delete =Box.createHorizontalBox();
- JButton deleteme = new JButton("Delete Entry");
- deleteme.addActionListener(new DeleteHandler());
- delete.add(deleteme);
- //panel.add(delete);
- dataTable.addMouseListener(new MyMouseListener());
- panel.add(delete, BorderLayout.PAGE_END);
- return panel;
- }
- //////////////////////////////////////////////////////////////////////////////
- /// MOUSE HANDLER CLASS ///
- class DeleteHandler implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- int rowIndex = dataTable.getSelectedRow();
- if(rowIndex == -1) return;
- String key = ((String)dataTable.getValueAt(rowIndex,0)) +
- ((String)dataTable.getValueAt(rowIndex,1)) +
- ((String)dataTable.getValueAt(rowIndex,2));
- if(ps.remove(key))
- dataTable.deleteRow(rowIndex);
- else
- JOptionPane.showMessageDialog(parentReference,
- "Error, could not find record to delete.",
- "Error",JOptionPane.ERROR_MESSAGE);
- }
- }
- /////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////
- /////////////////////////////////////////////////////////////////////////////
- public class MyMouseListener extends MouseAdapter {
- public void mouseClicked(MouseEvent e) {
- if(e.getClickCount() < 2) return;
- Point p = e.getPoint();
- if(cardShowing.equals("View Contacts")){
- int row = dataTable.rowAtPoint(p);
- JFrame parent = new JFrame();
- ///below just grabs each row and puts into long string.
- //not sure but we need to make it look better on pop up
- name += " " +dataTable.getValueAt(row,0);
- name1 += " " +dataTable.getValueAt(row,1);
- name2 += " " +dataTable.getValueAt(row,2);
- name3 += " " +dataTable.getValueAt(row,3);
- name4 += " " +dataTable.getValueAt(row,4);
- name5 += " " +dataTable.getValueAt(row,5);
- name6 += dataTable.getValueAt(row,6);
- String msg;
- msg = name +"\n" + name1 +"\n" +name2 +"\n" + name3 + "\n" + name4 + "\n"+ name5 + "\n"+name6 +"\n";
- JOptionPane optionPane = new JOptionPane();
- optionPane.setMessage(msg);
- optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
- JDialog dialog = optionPane.createDialog(null, "Contact Info");
- dialog.setVisible(true);
- /*
- name += dataTable.getValueAt(row,0);
- name2 += dataTable.getValueAt(row,1);
- name3 += dataTable.getValueAt(row,2);
- String ok;
- ok = name + name2 + name3 ;
- String helloString = new String(ok);
- JOptionPane.showMessageDialog(parent,"Name:" + helloString );
- */
- }
- /*
- else if(cardShowing.equals("FirstName")) {
- int row = dataTable.rowAtPoint(p);
- //MyTableModel model = (MyTableModel) dataTable.getModel();
- String name = (String) dataTable.getValueAt(row,1);
- name += " " + dataTable.getValueAt(row,0);
- JOptionPane.showMessageDialog(frame, "Editing " + name);
- }
- */
- }
- }
- ////////////////////////////////////////////////////////
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- public static void main(String [] args) {
- new prog2();
- }
- }
Expand|Select|Wrap|Line Numbers
- /*
- */
- import java.io.*;
- import java.util.*;
- public class Contact implements Comparable<Contact>,Serializable{
- public static final int NUM_FIELDS = 13;
- public static final int F_NAME = 0;
- public static final int L_NAME = 1;
- public static final int GROUP = 2;
- public static final int SCREEN_NAME = 3;
- public static final int PRIMARY_PHONE = 4;
- public static final int ADDRESS = 5;
- public static final int CITY = 6;
- public static final int STATE = 7;
- public static final int ZIP = 8;
- public static final int PRIMARY_EMAIL = 9;
- public static final int SECONDARY_EMAIL = 10;
- //public static final int SCREEN_NAME = 9;
- //public static final int PRIMARY_PHONE = 10;
- public static final int SECONDARY_PHONE = 11;
- public static final int PRIMARY_COMMENTS = 12;
- //public static final int DROP_DOWN = 13;
- private String[] values;
- public Contact(Vector<String> v){
- values = new String[NUM_FIELDS];
- for(int i = 0; i < NUM_FIELDS; i++) values[i] = v.elementAt(i).trim();
- }//end Contact(Vector<String> v)
- public String getKey(){
- //return values[PRIMARY_PHONE] + values[F_NAME] + values[L_NAME] + values[NICK_NAME];
- return values[F_NAME]+values[L_NAME]+ values[GROUP];
- }// end getKey()
- public String getValue(int whichOne){
- return values[whichOne];
- }//end getValue(int)
- public Vector<String> getValueVector(){
- Vector<String> tmp = new Vector<String>(NUM_FIELDS);
- for(int i = 0; i < NUM_FIELDS; i++) tmp.add(values[i]);
- return tmp;
- }//end getVectorValue()
- public void setValue(int whichOne, String newValue){
- values[whichOne] = newValue;
- }//end setValue()
- public int compareTo(Contact s){
- //String a= values[L_NAME] + values[F_NAME]+ values[ADDRESS];
- //String b= s.values[L_NAME] + s.values[F_NAME]+ s.values[ADDRESS];
- //String a= values[PRIMARY_PHONE] + values[F_NAME] + values[L_NAME] + values[NICK_NAME];
- //String b = s.values[PRIMARY_PHONE] + s.values[F_NAME] + s.values[L_NAME] + values[NICK_NAME];
- String a = values[F_NAME] + values[L_NAME]+ values[GROUP];
- String b = s.values[F_NAME] + s.values[L_NAME]+ s.values[GROUP];
- return a.compareTo(b);
- }//end compareTo()
- /*Comparable<Contatct>{
- }//end Comparable<Contact>*/
- }
- //end class Contact
Expand|Select|Wrap|Line Numbers
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.table.*;
- import java.util.*;
- /**
- * A custom JTable that supports additional functionality. The following
- * features are supported:
- * <ul>
- * <li>Alternating row backgrounds</li>
- * <li>Custom font and background color for column headers
- * <li>Columns may be made sortable. The table sets an alternate
- * background color for the clicked column</li>
- * <li>New rows may be added dynamically</li>
- * <li>Rows may be deleted dynamically</li>
- * </ul>
- * @version 1.0
- * @author Alan Riggins
- */
- public class JCustomTable extends JTable {
- private Object [][] data;
- private Object [] colNames;
- private int numRows, numCols;
- private Color firstRowColor = Color.white;
- private Color secondRowColor = Color.white;
- private Color columnBackgroundClickedColor = Color.gray;
- private Color headerColumnBackgroundColor = Color.gray;
- private JCustomTable parentReference;
- private int columnToSort = 0;
- private Font headerFont = null;
- /** Creates a new JCustomTable and populates it with the
- * parameter data.
- * @param data A 2D array of class Object.
- * @param columnNames An array containing the names of each
- * column
- */
- public JCustomTable(Object [][] data, Object [] columnNames) {
- super(data,columnNames);
- this.data = data;
- colNames = columnNames;
- setModel(new MyTableModel());
- numRows = data.length;
- numCols = colNames.length;
- parentReference = this;
- }
- /** Creates a new JCustomTable and populates it with the
- * parameter data.
- * @param data A Vector of vectors representing the table data
- * @param columnNames A vector containing the names of each column
- */
- public JCustomTable(Vector vData, Vector vColumnNames) {
- data = new Object[vData.size()][vColumnNames.size()];
- colNames = new Object[vColumnNames.size()];
- for(int i=0; i < vData.size(); i++)
- for(int j=0; j < vColumnNames.size(); j++)
- data[i][j] = ((Vector)vData.elementAt(i)).elementAt(j);
- for(int i=0; i < vColumnNames.size(); i++)
- colNames[i] = vColumnNames.elementAt(i);
- setModel(new MyTableModel());
- numRows = data.length;
- numCols = colNames.length;
- parentReference = this;
- }
- /** Sets the background color of the table header
- * @param background The Color to use for the background
- */
- public void setTableHeaderBackground(Color background) {
- JTableHeader header = getTableHeader();
- headerColumnBackgroundColor = background;
- header.setBackground(headerColumnBackgroundColor);
- }
- /** Allows the user to select a custom font for the table header.
- * @param f The font to use
- */
- public void setTableHeaderFont(Font f) {
- JTableHeader header = getTableHeader();
- header.setFont(f);
- headerFont = f;
- }
- /** Allows the user to stripe table rows with alternating
- * background color. This often helps the appearance of
- * the table, and makes records easier to see
- * @param c1 c1 is the background color of rows 0,2,4 ...
- * @param c2 c2 is the background color of row 1,3,5 ...
- */
- public void setCustomRowColors(Color c1, Color c2) {
- firstRowColor = c1;
- secondRowColor = c2;
- repaint();
- }
- /** Inserts a new row into the table dynamically.
- * @param d is an array containing the data to insert. The data
- * should be in the same order as the column names
- * @exception Throws a RuntimeException if the number of elements
- * in the array does not match the number of columns in the table.
- */
- public void insertRow(Object [] d) {
- //if(d.length != numCols)
- // throw new RuntimeException("Error, wrong number of columns in insertRow");
- int oldSize = data.length;
- Object [][] tmp = new Object[oldSize+1][numCols];
- for(int i=0; i < oldSize; i++)
- for(int j=0; j < numCols; j++)
- tmp[i][j] = data[i][j];
- for(int i=0; i < numCols; i++)
- tmp[numRows][i] = d[i];
- data = tmp;
- numRows++;
- MyTableModel model = (MyTableModel) getModel();
- for(int i=0; i < numCols; i++)
- model.setValueAt(data[data.length-1][i],data.length-1,i);
- model.fireTableDataChanged();
- }
- /** Deletes a row from the table dynamically.
- * @param whichRow is the number of the row to delete. The number
- * is zero-based. i.e. the first row is row #0
- * @exception Throws a RuntimeException if the number of elements
- * in the array does not match the number of columns in the table.
- */
- public void deleteRow(int whichRow) {
- if(whichRow >= numRows)
- throw new RuntimeException("Error, attempt to remove non-existent row.");
- MyTableModel model = (MyTableModel) getModel();
- Object [][] tmp = new Object[data.length-1][numCols];
- for(int i=whichRow; i < data.length-1; i++)
- data[i] = data[i+1];
- for(int i=0; i < tmp.length; i++) {
- for(int j=0; j < numCols; j++) {
- tmp[i][j] = data[i][j];
- model.setValueAt(tmp[i][j],i,j);
- }
- }
- data = tmp;
- numRows = data.length;
- model.fireTableDataChanged();
- }
- /** Makes each column sortable. If the user clicks on a column
- * header, the background color changes to signal its selection.
- * All table data must implement the Comparable interface. This
- * method makes all columns sortable, with no way to restrict
- * sorting to certain rows.
- * @param selectedBackgroundColor is the Color that the header cell
- * background will be set to when that column has been selected.
- */
- public void setColumnsSortable(Color selectedBackgroundColor) {
- columnBackgroundClickedColor = selectedBackgroundColor;
- JTableHeader header = getTableHeader();
- header.setUpdateTableInRealTime(true);
- header.addMouseListener(new MyColumnListener());
- }
- public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
- Component c = super.prepareRenderer(renderer,row,col);
- if((row&1) == 0)
- c.setBackground(firstRowColor);
- else
- c.setBackground(secondRowColor);
- return c;
- }
- public void sortColumn(int whichOne) {
- columnToSort = whichOne;
- sortData();
- MyTableModel model = (MyTableModel) getModel();
- for(int i=0; i < data.length; i++)
- for(int j=0; j < numCols; j++)
- model.setValueAt(data[i][j],i,j);
- repaint();
- }
- private void sortData() {
- Vector v = new Vector();
- for(int i=0; i < data.length; i++)
- v.add(data[i]);
- Collections.sort(v, new DataComparator());
- for(int i=0; i < data.length; i++)
- data[i] = (Object []) v.elementAt(i);
- }
- class DataComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- Object[] s1 = (Object []) o1;
- Object[] s2 = (Object []) o2;
- return ((Comparable)s1[columnToSort]).compareTo(s2[columnToSort]);
- }
- }
- ///////////////////////////////////////////////////////////////////
- public class MyTableModel extends AbstractTableModel {
- public MyTableModel() {
- }
- public String getColumnName(int col) {
- return (String) colNames[col];
- }
- public boolean isCellEditable(int row, int col) {
- return false;
- }
- public void setValueAt(Object value, int row, int col) {
- data[row][col] = value;
- fireTableDataChanged();
- repaint();
- fireTableCellUpdated(row,col);
- }
- public Object getValueAt(int row, int col) {
- return data[row][col];
- }
- public int getColumnCount() {
- return colNames.length;
- }
- public int getRowCount() {
- return data.length;
- }
- }
- /////////////////////////////////////////////////////////////////////////
- public class MyColumnListener extends MouseAdapter {
- private TableCellRenderer r ;
- private int lastIndexSet = -1;
- public MyColumnListener() {
- TableColumnModel columnModel = getColumnModel();
- TableColumn column = columnModel.getColumn(0);
- r = column.getHeaderRenderer();
- }
- public void mouseClicked(MouseEvent e) {
- JTableHeader header = parentReference.getTableHeader();
- TableColumnModel columnModel = parentReference.getColumnModel();;
- int columnModelIndex = columnModel.getColumnIndexAtX(e.getX());
- int modelIndex =
- columnModel.getColumn(columnModelIndex).getModelIndex();
- if(modelIndex < 0) return;
- parentReference.sortColumn(modelIndex);
- TableColumn column = columnModel.getColumn(modelIndex);
- column.setHeaderRenderer(new MyCheckedHeaderRenderer());
- if(lastIndexSet != -1 && lastIndexSet != modelIndex) {
- column = columnModel.getColumn(lastIndexSet);
- column.setHeaderRenderer(r);
- }
- lastIndexSet = modelIndex;
- MyTableModel model = (MyTableModel) parentReference.getModel();
- model.fireTableDataChanged();
- }
- }
- public class MyCheckedHeaderRenderer extends DefaultTableCellRenderer {
- public Component getTableCellRendererComponent(JTable table, Object value,
- boolean isSelected, boolean hasFocus, int row, int column) {
- JLabel l = new JLabel(((String)value), SwingConstants.CENTER);
- l.setOpaque(true);
- l.setBackground(columnBackgroundClickedColor);
- if(headerFont != null)
- l.setFont(headerFont);
- return l;
- }
- }
- ////////////////////////////////////////////////////////////////////////
- }
Expand|Select|Wrap|Line Numbers
- /* PersistentStorage.java
- A class that hold data, and keeps it persistent by syncing the
- data in memory with a disk file.
- Everything passed to this class for storage must implement Serializable.
- This class is a Dictionary that uses KEY=VALUE pairs. The class does
- not accept duplicate entries.
- Parameterized types are used for type safety. The Object iostreams
- do not support parameterized types, so expect a class cast warning.
- Alan Riggins
- CS551, Summer 09
- */
- import java.util.*;
- import java.io.*;
- public class PersistentStorage<K,V> {
- private TreeMap<K,V> map;
- private final String filename = "persistent_data.dat";
- public PersistentStorage() {
- try {
- readMapFromDisk();
- }
- catch(Exception e) {
- map = new TreeMap<K,V>();
- }
- }
- // Inserts the given KEY=VALUE pair in the dictionary, and returns
- // TRUE on success. If the KEY is a duplicate, the method takes
- // no action and returns FALSE.
- public boolean insert(K key, V value) {
- if(map.containsKey(key))
- return false;
- map.put(key,value);
- writeMapToDisk();
- return true;
- }
- // WARNING: The user may use the returned Object reference to
- // modify either the key or value. In such cases, the saveState()
- // method must be called to insure the data on disk is in sync.
- // returns the VALUE associated with the KEY, null if the KEY is
- // not in the map.
- public V getValue(K key) {
- return map.get(key);
- }
- public boolean containsKey(K key) {
- return map.containsKey(key);
- }
- public int size() {
- return map.size();
- }
- // Removes the KEY=VALUE pair associated with the KEY and returns
- // TRUE if it is found and removed, otherwise returns FALSE.
- public boolean remove(K key) {
- if(map.remove(key) == null)
- return false;
- writeMapToDisk();
- return true;
- }
- public void makeEmpty() {
- map.clear();
- writeMapToDisk();
- }
- // After an edit, you must save state to disk
- public void saveState() {
- writeMapToDisk();
- }
- private void writeMapToDisk() {
- try {
- ObjectOutputStream out = new ObjectOutputStream(
- new BufferedOutputStream(
- new FileOutputStream(filename)));
- out.writeObject(map);
- out.close();
- }
- catch(Exception e) {
- throw new RuntimeException("Error, cannot write data to disk.");
- }
- }
- private void readMapFromDisk() {
- try {
- ObjectInputStream in = new ObjectInputStream
- (new BufferedInputStream
- (new FileInputStream
- (filename)));
- map = (TreeMap<K,V>) in.readObject();
- in.close();
- }
- catch(Exception e) {
- throw new RuntimeException("Error, cannot read data from disk.");
- }
- }
- ///////////////////////////////////////////////////////////////////////////
- // The iterators return KEYS in sorted order as defined by Comparable<K>
- // for the KEYS. VALUES are returned in KEY sorted order.
- public Iterator<K> keys() {
- return map.keySet().iterator();
- }
- public Iterator<V> values() {
- return map.values().iterator();
- }
- ///////////////////////////////////////////////////////////////////////////
- } // end class