By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,490 Members | 1,489 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,490 IT Pros & Developers. It's quick & easy.

java array help

P: 54
so here is my problem...in a contact manager i am trying to complete i have ran into an error..we have lots of code because we have some from class which we can use...anyways i keep getting an error when i do the following. if you add a contact with up to 13 fields it will be stored in a data structure. i have a tabbed pane that will show six of the 13 fields for that contact. when you double click the contact i want it to pop up and show all 13 fields worth of info..well i can do it for up to 5 fields..but once i add a sixth field i get the following error.. "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 6 >= 6


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
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.border.*;
  5. import javax.swing.table.*;
  6. import java.util.*;
  7.  
  8. public class prog2 extends JFrame {
  9.  
  10.     private JPanel mainPanel;
  11.     Box horizontalbox;
  12.     private JLabel sname;
  13.     private JTextField [] fields;
  14.     private JButton submit, clear,sub;
  15.     private PersistentStorage ps;
  16.     private JFrame parentReference;
  17.     private JLabel statusLabel;
  18.     private JCustomTable dataTable;
  19.  
  20.     private JTable table;
  21.     private String cardShowing;
  22.     private JFrame frame = this;
  23.       private String name,name1,name2,name3,name4,name5,name6,name7,name8,name9;
  24.  
  25.     public prog2() {
  26.         fields = new JTextField[Contact.NUM_FIELDS];
  27.         ps = new PersistentStorage();
  28.         parentReference = this;
  29.         statusLabel = new JLabel();
  30.  
  31.         setWindowAttributes();
  32.         setLookAndFeel();
  33.         addMainPanel();
  34.         addComponents();
  35.         setVisible(true);
  36.         }
  37.  
  38. //////////////////////////////////////////////////////////////////////////////
  39. /// MAIN METHODS ///
  40. //////////////////////////////////////////////////////////////////////////////
  41.  
  42.     private void setWindowAttributes() {
  43.         setTitle("Personal Contact Manager");
  44.         setSize(900,450);
  45.         setLocation(50,50);
  46.         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  47.         }
  48.  
  49.     private void setLookAndFeel() {
  50.         try {
  51.             UIManager.setLookAndFeel(
  52.             UIManager.getSystemLookAndFeelClassName());
  53.             //UIManager.getCrossPlatformLookAndFeelClassName());
  54.             }
  55.         catch(Exception e) {
  56.         System.out.println("Sorry, LookAndFeel not found.  Available LAFs are\n");
  57.         UIManager.LookAndFeelInfo [] x = UIManager.getInstalledLookAndFeels();
  58.         for(int i=0; i < x.length; i++)
  59.             System.out.println(x[i]);
  60.             }
  61.         }
  62.  
  63.     private void addMainPanel() {
  64.         mainPanel = new JPanel();
  65.         mainPanel.setLayout(new FlowLayout());
  66.         mainPanel.setBackground(new Color(240,240,240));
  67.         add(mainPanel);
  68.         }
  69.  
  70.  
  71.     private void make(){
  72.  
  73.  
  74.  
  75. }
  76.     private void addComponents() {
  77.  
  78.     Box name = Box.createHorizontalBox();
  79.  
  80.     //this is code for drop down menu.
  81.     //String[] dropDown  = { "Friends", "Family", "School", "Work", "Church"  };
  82.     //JComboBox dropDownMenu = new JComboBox(dropDown);
  83.  
  84.  
  85.  
  86.     //code below is for name boxes.
  87.     JLabel first = new JLabel("First: ");
  88.     JLabel last = new JLabel("Last: ");
  89.     JLabel nick = new JLabel("Group: ");
  90.     //JTextField textFieldfname = new JTextField("", 7);
  91.     fields[Contact.F_NAME]= new JTextField(7);
  92.     //JTextField textFieldlname = new JTextField("", 7);
  93.     fields[Contact.L_NAME]= new JTextField(7);
  94.     //JTextField textFieldnickname = new JTextField("", 7);
  95.     fields[Contact.GROUP]= new JTextField(7);
  96.     name.setPreferredSize(new Dimension (850,60));
  97.     name.setMaximumSize(new Dimension (850,60));
  98.     name.add(first);
  99.     //name.add(textFieldfname);
  100.     name.add(fields[Contact.F_NAME]);
  101.     name.add(Box.createRigidArea(new Dimension(5,0)));
  102.     name.add(last);
  103.     //name.add(textFieldlname);
  104.     name.add(fields[Contact.L_NAME]);
  105.     name.add(Box.createRigidArea(new Dimension(5,0)));
  106.     name.add(nick);
  107.     //name.add(textFieldnickname);
  108.     name.add(fields[Contact.GROUP]);
  109.     name.add(Box.createRigidArea(new Dimension(5,0)));
  110.     //name.add(dropDownMenu);
  111.     name.add(Box.createRigidArea(new Dimension(5,0)));
  112.     name.setBorder(BorderFactory.createTitledBorder("Contact Info"));
  113.     mainPanel.add(name);
  114.     mainPanel.add(Box.createRigidArea(new Dimension(1000,10)));
  115.  
  116.  
  117.  
  118.    //creating tabbed pane
  119.  
  120.  JTabbedPane ContactPane = new JTabbedPane();
  121.  JPanel contactPanel = new JPanel();
  122.  JPanel listPanel= new JPanel();
  123.  listPanel.setLayout(new BorderLayout());
  124.  ContactPane.setPreferredSize(new Dimension (875,325));
  125.  ContactPane.setMaximumSize(new Dimension(875,325));
  126.  Box Contacts = Box.createHorizontalBox();
  127.  ContactPane.addTab("Contact Info",contactPanel);
  128.  ContactPane.addTab("View Contacts", makeViewTable());
  129.  //ContactPane.addTab("Contact List",listPanel);
  130.  Contacts.add(ContactPane);
  131.  mainPanel.add(Contacts);
  132.  mainPanel.add(Box.createRigidArea(new Dimension(1000,0)));
  133.  cardShowing = "View Contacts";
  134.     //ContactPane.addMouseListener(new MyMouseListener());
  135.    //adding contact info to tabbed pane
  136.  
  137.    JLabel Address = new JLabel("Address: ");
  138.    fields[Contact.ADDRESS] = new JTextField(15);
  139.  
  140.    JLabel City = new JLabel("City: ");
  141.    fields[Contact.CITY] = new JTextField(10);
  142.  
  143.    JLabel State = new JLabel("State: ");
  144.    fields[Contact.STATE] = new JTextField(5);
  145.  
  146.    JLabel Zip = new JLabel("Zip: ");
  147.    fields[Contact.ZIP] = new JTextField(5);
  148.  
  149.    JLabel Email = new JLabel("Primary Email: ");
  150.    fields[Contact.PRIMARY_EMAIL] = new JTextField(18);
  151.  
  152.    JLabel Email2 = new JLabel("Secondary Email: ");
  153.    fields[Contact.SECONDARY_EMAIL] = new JTextField(18);
  154.  
  155.    sname = new JLabel("ScreenName:");
  156.    fields[Contact.SCREEN_NAME] = new JTextField(10);
  157.  
  158.    JLabel Phone1 = new JLabel("Primary Phone:");
  159.    fields[Contact.PRIMARY_PHONE] = new JTextField(10);
  160.  
  161.    JLabel Phone2 = new JLabel("Secondary Phone: ");
  162.    fields[Contact.SECONDARY_PHONE] = new JTextField(10);
  163.  
  164.    contactPanel.add(Box.createRigidArea(new Dimension(0,8)));
  165.    contactPanel.add(Address);
  166.    contactPanel.add(fields[Contact.ADDRESS]);
  167.  
  168.    contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
  169.    contactPanel.add(City);
  170.    contactPanel.add(fields[Contact.CITY]);
  171.  
  172.    contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
  173.    contactPanel.add(State);
  174.    contactPanel.add(fields[Contact.STATE]);
  175.  
  176.    contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
  177.    contactPanel.add(Zip);
  178.    contactPanel.add(fields[Contact.ZIP]);
  179.  
  180.    contactPanel.add(Box.createRigidArea(new Dimension(1000,15)));
  181.    contactPanel.add(Email);
  182.    contactPanel.add(fields[Contact.PRIMARY_EMAIL]);
  183.  
  184.    contactPanel.add(Box.createRigidArea(new Dimension(30,0)));
  185.    contactPanel.add(Email2);
  186.    contactPanel.add(fields[Contact.SECONDARY_EMAIL]);
  187.  
  188.    contactPanel.add(Box.createRigidArea(new Dimension(1000,15)));
  189.    contactPanel.add(sname);
  190.    contactPanel.add(fields[Contact.SCREEN_NAME]);
  191.  
  192.    contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
  193.    contactPanel.add(Phone1);
  194.    contactPanel.add(fields[Contact.PRIMARY_PHONE]);
  195.  
  196.    contactPanel.add(Box.createRigidArea(new Dimension(5,0)));
  197.    contactPanel.add(Phone2);
  198.    contactPanel.add(fields[Contact.SECONDARY_PHONE]);
  199.  
  200.    contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
  201.      //contactPanel.addMouseListener(new MyMouseListener());
  202.     //comment field
  203.    JLabel comments = new JLabel("Comments: ");
  204.    //JTextArea commentField = new JTextArea(5,30);
  205.    fields[Contact.PRIMARY_COMMENTS] = new JTextField(30);
  206.    //commentField.setLineWrap(true);
  207.    //commentField.setBorder(new LineBorder(Color.black,1));
  208.    contactPanel.add(comments);
  209.    //contactPanel.add(commentField);
  210.    contactPanel.add(fields[Contact.PRIMARY_COMMENTS]);
  211.    contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
  212.  
  213.  
  214.  
  215. //submit and clear buttons
  216.     Box buttonPane=Box.createHorizontalBox();
  217.     submit = new JButton("Submit");
  218.     clear = new JButton("Clear");
  219.    //submit.addActionListener(new SubmitHandler());
  220.    //submit.setMaximumSize(new Dimension(40,40));
  221.  
  222.    buttonPane.createHorizontalGlue();
  223.    submit.addActionListener(new SubmitHandler());
  224.  
  225.    buttonPane.add(submit);
  226.    buttonPane.createHorizontalGlue();
  227.     clear.addActionListener(new ActionListener() {
  228.             public void actionPerformed(ActionEvent e) {
  229.                 for(int i=0; i < Contact.NUM_FIELDS; i++)
  230.                     fields[i].setText("");
  231.                 statusLabel.setText("");
  232.                 }
  233.             });
  234.    buttonPane.add(clear);
  235.    buttonPane.createHorizontalGlue();
  236.    contactPanel.add(buttonPane);
  237.    contactPanel.add(Box.createRigidArea(new Dimension(1000,20)));
  238.    contactPanel.add(statusLabel);
  239.          }
  240. //////////////////////////////////////////////////////////////////////////////
  241. /// GUI BUILD AND PLACE
  242. //////////////////////////////////////////////////////////////////////////////
  243.  
  244.  class SubmitHandler implements ActionListener {
  245.         public void actionPerformed(ActionEvent e)
  246.  
  247.          {
  248.  
  249.  
  250.                 if(fields[0].getText().trim().length() == 0 ||
  251.                    fields[1].getText().trim().length() == 0 ||
  252.                    fields[2].getText().trim().length() == 0) {
  253.                    statusLabel.setText("Incomplete Record, not saved.");
  254.                    return;
  255.  
  256.                    }
  257.  
  258.             Vector<String> tmp = new Vector<String>(Contact.NUM_FIELDS);
  259.             for(int i=0; i < Contact.NUM_FIELDS; i++)
  260.                 tmp.add(fields[i].getText());
  261.             Contact c = new Contact(tmp);
  262.             if(ps.insert(c.getKey(),c)) {
  263.                 Object [] newData = new Object[fields.length];
  264.                 for(int i=0; i < fields.length; i++)
  265.                     newData[i] = fields[i].getText().trim();
  266.                 dataTable.insertRow(newData);
  267.  
  268.                 for(int i=0; i < Contact.NUM_FIELDS; i++)
  269.                     fields[i].setText("");
  270.                 statusLabel.setText("Record saved");
  271.  
  272.                 }
  273.             else {
  274.                 statusLabel.setText("");
  275.                 JOptionPane.showMessageDialog(parentReference, "Sorry, duplicate entry.",
  276.                         "Error",JOptionPane.ERROR_MESSAGE);
  277.  
  278.                 }
  279.             }
  280.         }
  281.  
  282.  
  283. //////////////////////////////////////////////////////////////////////////////
  284. /// HELPER METHODS ///
  285. //////////////////////////////////////////////////////////////////////////////
  286.  private JPanel makeViewTable() {
  287.         JPanel panel = new JPanel();
  288.         JPanel listPanel= new JPanel();
  289.         panel.setLayout(new BorderLayout());
  290.         Vector<String> columnNames = new Vector<String>(Contact.NUM_FIELDS);
  291.         columnNames.add("First Name");
  292.         columnNames.add("Last Name");
  293.         columnNames.add("Group");
  294.         //columnNames.add("Address");
  295.         //columnNames.add("City");
  296.         //columnNames.add("State");
  297.         //columnNames.add("Zip");
  298.  
  299.         //columnNames.add("Email 2");
  300.  
  301.         columnNames.add("Phone 1");
  302.         columnNames.add("Email 1");
  303.         columnNames.add("ScreenName");
  304.         //columnNames.add("Phone 2");
  305.         //columnNames.add("Comments");
  306.  
  307.         Vector<Vector<String>> fieldData = new Vector<Vector<String>>(Contact.NUM_FIELDS);
  308.         Iterator<Contact> iter = ps.values();
  309.         while(iter.hasNext()) {
  310.             Contact tmp = iter.next();
  311.             Vector<String> tmpV = tmp.getValueVector();
  312.             fieldData.add(tmpV);
  313.             }
  314.         dataTable = new JCustomTable(fieldData, columnNames);
  315.         dataTable.setTableHeaderBackground(new Color(255,200,200));
  316.         dataTable.setFont(new Font("Arial",Font.BOLD, 14));
  317.         dataTable.setCustomRowColors(Color.white, new Color(220,220,255));
  318.         dataTable.setColumnsSortable(new Color(220,220,255));
  319.         //dataTable.setPreferredSize(new Dimension(400,400));
  320.         //dataTable.setMaximumSize(new Dimension (400,400));
  321.  
  322.         JScrollPane scrollPane = new JScrollPane(dataTable);
  323.         panel.add(scrollPane, BorderLayout.CENTER);
  324.      panel.addMouseListener(new MyMouseListener());
  325.     Box delete =Box.createHorizontalBox();
  326.     JButton deleteme = new JButton("Delete Entry");
  327.     deleteme.addActionListener(new DeleteHandler());
  328.     delete.add(deleteme);
  329.     //panel.add(delete);
  330.  
  331.     dataTable.addMouseListener(new MyMouseListener());
  332.     panel.add(delete, BorderLayout.PAGE_END);
  333.  
  334.         return panel;
  335.         }
  336.  
  337.  
  338.  
  339. //////////////////////////////////////////////////////////////////////////////
  340. /// MOUSE HANDLER CLASS ///
  341.  
  342. class DeleteHandler implements ActionListener {
  343.         public void actionPerformed(ActionEvent e) {
  344.            int rowIndex = dataTable.getSelectedRow();
  345.            if(rowIndex == -1) return;
  346.  
  347.            String key = ((String)dataTable.getValueAt(rowIndex,0)) +
  348.                         ((String)dataTable.getValueAt(rowIndex,1)) +
  349.                         ((String)dataTable.getValueAt(rowIndex,2));
  350.  
  351.  
  352.            if(ps.remove(key))
  353.                dataTable.deleteRow(rowIndex);
  354.            else
  355.                 JOptionPane.showMessageDialog(parentReference,
  356.                     "Error, could not find record to delete.",
  357.                     "Error",JOptionPane.ERROR_MESSAGE);
  358.            }
  359.     }
  360.  
  361. /////////////////////////////////////////////////////////////////////////////
  362.  
  363. //////////////////////////////////////////////////////////////////////////////
  364.  
  365. ///////////////////////////////////////////////////////////////////////////////
  366.  
  367.  
  368. /////////////////////////////////////////////////////////////////////////////
  369.  
  370.   public class MyMouseListener extends MouseAdapter {
  371.         public void mouseClicked(MouseEvent e) {
  372.             if(e.getClickCount() < 2) return;
  373.             Point p = e.getPoint();
  374.             if(cardShowing.equals("View Contacts")){
  375.  
  376.  
  377.                 int row = dataTable.rowAtPoint(p);
  378.                 JFrame parent = new JFrame();
  379.  
  380.  
  381.  
  382.                 ///below just grabs each row and puts into long string.
  383.                 //not sure but we need to make it look better on pop up
  384.  
  385.                 name  += " " +dataTable.getValueAt(row,0);
  386.         name1 += " " +dataTable.getValueAt(row,1);
  387.         name2 += " " +dataTable.getValueAt(row,2);
  388.         name3 += " " +dataTable.getValueAt(row,3);
  389.         name4    += " " +dataTable.getValueAt(row,4);
  390.         name5    += " " +dataTable.getValueAt(row,5);  
  391.         name6    += dataTable.getValueAt(row,6);        
  392.        String msg;
  393.          msg = name +"\n" + name1 +"\n" +name2 +"\n" + name3 + "\n" + name4 + "\n"+ name5 + "\n"+name6 +"\n";       
  394.     JOptionPane optionPane = new JOptionPane();
  395.     optionPane.setMessage(msg);
  396.     optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
  397.     JDialog dialog = optionPane.createDialog(null, "Contact Info");
  398.     dialog.setVisible(true);
  399.  
  400.  
  401. /*
  402.  
  403.         name +=  dataTable.getValueAt(row,0);
  404.         name2 +=  dataTable.getValueAt(row,1);
  405.         name3 += dataTable.getValueAt(row,2);                
  406.         String ok;        
  407.         ok = name  + name2  + name3 ;
  408.  
  409.         String helloString = new String(ok);
  410.  
  411.  
  412.                 JOptionPane.showMessageDialog(parent,"Name:" + helloString );
  413.  
  414.          */    
  415.                 }
  416.         /*
  417.             else if(cardShowing.equals("FirstName")) {
  418.                 int row = dataTable.rowAtPoint(p);
  419.                 //MyTableModel model = (MyTableModel) dataTable.getModel();
  420.                 String name = (String) dataTable.getValueAt(row,1);
  421.                 name += " " + dataTable.getValueAt(row,0);
  422.                 JOptionPane.showMessageDialog(frame, "Editing " + name);
  423.                 } 
  424.           */           
  425.             }
  426.         }
  427.  
  428.  
  429.  
  430.  ////////////////////////////////////////////////////////
  431.  
  432. /////////////////////////////////////////////////////////////////////////////////////////////////////
  433.  
  434.  
  435.     public static void main(String [] args) {
  436.         new prog2();
  437.         }
  438.     }

Expand|Select|Wrap|Line Numbers
  1. /*
  2.  
  3. */
  4.  
  5. import java.io.*;
  6. import java.util.*;
  7.  
  8.  public class Contact implements Comparable<Contact>,Serializable{
  9.  
  10.     public static final int NUM_FIELDS = 13;
  11.     public static final int F_NAME = 0;
  12.     public static final int L_NAME = 1;
  13.     public static final int GROUP = 2;
  14.     public static final int SCREEN_NAME = 3;
  15.     public static final int PRIMARY_PHONE = 4;
  16.     public static final int ADDRESS = 5;
  17.     public static final int CITY = 6;
  18.     public static final int STATE = 7;
  19.     public static final int ZIP = 8;
  20.     public static final int PRIMARY_EMAIL = 9;
  21.     public static final int SECONDARY_EMAIL = 10;
  22.     //public static final int SCREEN_NAME = 9;
  23.     //public static final int PRIMARY_PHONE = 10;
  24.     public static final int SECONDARY_PHONE = 11;
  25.     public static final int PRIMARY_COMMENTS = 12;
  26.     //public static final int DROP_DOWN = 13;
  27.  
  28.     private String[] values;
  29.  
  30.     public Contact(Vector<String> v){
  31.  
  32.  
  33.  
  34.         values = new String[NUM_FIELDS];
  35.         for(int i = 0; i < NUM_FIELDS; i++) values[i] = v.elementAt(i).trim();
  36.  
  37.     }//end Contact(Vector<String> v)
  38.  
  39.     public String getKey(){
  40.  
  41.         //return values[PRIMARY_PHONE] + values[F_NAME] + values[L_NAME] + values[NICK_NAME];
  42.         return values[F_NAME]+values[L_NAME]+ values[GROUP];
  43.     }// end getKey()
  44.  
  45.     public String getValue(int whichOne){
  46.  
  47.         return values[whichOne];
  48.  
  49.     }//end getValue(int)
  50.  
  51.     public Vector<String> getValueVector(){
  52.  
  53.         Vector<String> tmp = new Vector<String>(NUM_FIELDS);
  54.  
  55.         for(int i = 0; i < NUM_FIELDS; i++) tmp.add(values[i]);
  56.  
  57.         return tmp;
  58.  
  59.     }//end getVectorValue()
  60.  
  61.     public void setValue(int whichOne, String newValue){
  62.  
  63.         values[whichOne] = newValue;
  64.  
  65.     }//end setValue()
  66.  
  67.     public int compareTo(Contact s){
  68.         //String a= values[L_NAME] + values[F_NAME]+ values[ADDRESS];
  69.         //String b= s.values[L_NAME] + s.values[F_NAME]+ s.values[ADDRESS];
  70.         //String a= values[PRIMARY_PHONE] + values[F_NAME] + values[L_NAME] + values[NICK_NAME];
  71.         //String b = s.values[PRIMARY_PHONE] + s.values[F_NAME] + s.values[L_NAME] + values[NICK_NAME];
  72.         String a = values[F_NAME] + values[L_NAME]+ values[GROUP];
  73.         String b = s.values[F_NAME] + s.values[L_NAME]+ s.values[GROUP];        
  74.             return a.compareTo(b);
  75.  
  76.     }//end compareTo()
  77.  
  78.     /*Comparable<Contatct>{
  79.  
  80.     }//end Comparable<Contact>*/
  81.  
  82.  
  83. }
  84. //end class Contact

Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.table.*;
  5. import java.util.*;
  6.  
  7. /**
  8.   * A custom JTable that supports additional functionality.  The following
  9.   * features are supported:
  10.   * <ul>
  11.   * <li>Alternating row backgrounds</li>
  12.   * <li>Custom font and background color for column headers
  13.   * <li>Columns may be made sortable.  The table sets an alternate
  14.   *    background color for the clicked column</li>
  15.   * <li>New rows may be added dynamically</li>
  16.   * <li>Rows may be deleted dynamically</li>
  17.   * </ul>
  18.   * @version 1.0
  19.   * @author Alan Riggins
  20. */  
  21.  
  22. public class JCustomTable extends JTable {
  23.     private Object [][] data;
  24.     private Object [] colNames;
  25.     private int numRows, numCols;
  26.     private Color firstRowColor = Color.white;
  27.     private Color secondRowColor = Color.white;
  28.     private Color columnBackgroundClickedColor = Color.gray;
  29.     private Color headerColumnBackgroundColor = Color.gray;
  30.     private JCustomTable parentReference;
  31.     private int columnToSort = 0;
  32.     private Font headerFont = null;
  33.  
  34.     /** Creates a new JCustomTable and populates it with the 
  35.       * parameter data.
  36.       * @param data   A 2D array of class Object.
  37.       * @param columnNames An array containing the names of each 
  38.       * column
  39.       */
  40.     public JCustomTable(Object [][] data, Object [] columnNames) {
  41.         super(data,columnNames);
  42.         this.data = data;
  43.         colNames = columnNames;        
  44.         setModel(new MyTableModel());
  45.  
  46.         numRows = data.length;
  47.         numCols = colNames.length;
  48.         parentReference = this;
  49.         }
  50.  
  51.     /** Creates a new JCustomTable and populates it with the 
  52.       * parameter data.
  53.       * @param data     A Vector of vectors representing the table data
  54.       * @param columnNames      A vector containing the names of each column
  55.       */        
  56.     public JCustomTable(Vector vData, Vector vColumnNames) {
  57.         data = new Object[vData.size()][vColumnNames.size()];
  58.         colNames = new Object[vColumnNames.size()];
  59.         for(int i=0; i < vData.size(); i++) 
  60.             for(int j=0; j < vColumnNames.size(); j++)
  61.                 data[i][j] = ((Vector)vData.elementAt(i)).elementAt(j);
  62.         for(int i=0; i < vColumnNames.size(); i++)
  63.             colNames[i] = vColumnNames.elementAt(i);
  64.         setModel(new MyTableModel());
  65.         numRows = data.length;
  66.         numCols = colNames.length;
  67.         parentReference = this;                        
  68.         }
  69.  
  70.     /** Sets the background color of the table header
  71.       * @param background  The Color to use for the background
  72.       */
  73.     public void setTableHeaderBackground(Color background) {
  74.         JTableHeader header = getTableHeader();
  75.         headerColumnBackgroundColor = background;
  76.         header.setBackground(headerColumnBackgroundColor);
  77.         }
  78.  
  79.     /** Allows the user to select a custom font for the table header.
  80.       * @param f    The font to use
  81.       */    
  82.     public void setTableHeaderFont(Font f) {
  83.         JTableHeader header = getTableHeader();
  84.         header.setFont(f);
  85.         headerFont = f;
  86.         }        
  87.  
  88.     /** Allows the user to stripe table rows with alternating 
  89.       * background color.  This often helps the appearance of 
  90.       * the table, and makes records easier to see
  91.       * @param c1   c1 is the background color of rows 0,2,4 ...
  92.       * @param c2   c2 is the background color of row 1,3,5 ...
  93.       */ 
  94.     public void setCustomRowColors(Color c1, Color c2) {
  95.         firstRowColor = c1;
  96.         secondRowColor = c2;
  97.         repaint();
  98.         }
  99.  
  100.     /** Inserts a new row into the table dynamically.
  101.       * @param d is an array containing the data to insert.  The data
  102.       * should be in the same order as the column names
  103.       * @exception Throws a RuntimeException if the number of elements
  104.       * in the array does not match the number of columns in the table.
  105.       */   
  106.     public void insertRow(Object [] d) {
  107.         //if(d.length != numCols)
  108.           //  throw new RuntimeException("Error, wrong number of columns in insertRow");
  109.         int oldSize = data.length;
  110.         Object [][] tmp = new Object[oldSize+1][numCols];
  111.         for(int i=0; i < oldSize; i++)
  112.             for(int j=0; j < numCols; j++)
  113.                 tmp[i][j] = data[i][j];
  114.         for(int i=0; i < numCols; i++)
  115.             tmp[numRows][i] = d[i];
  116.         data = tmp;
  117.         numRows++;
  118.         MyTableModel model = (MyTableModel) getModel();
  119.         for(int i=0; i < numCols; i++)
  120.             model.setValueAt(data[data.length-1][i],data.length-1,i);
  121.         model.fireTableDataChanged();        
  122.     } 
  123.  
  124.     /** Deletes a row from the table dynamically.
  125.       * @param whichRow is the number of the row to delete.  The number 
  126.       * is zero-based. i.e. the first row is row #0
  127.       * @exception Throws a RuntimeException if the number of elements
  128.       * in the array does not match the number of columns in the table.
  129.       */   
  130.     public void deleteRow(int whichRow) {
  131.         if(whichRow >= numRows)
  132.             throw new RuntimeException("Error, attempt to remove non-existent row.");
  133.         MyTableModel model = (MyTableModel) getModel();        
  134.         Object [][] tmp = new Object[data.length-1][numCols];        
  135.         for(int i=whichRow; i < data.length-1; i++)
  136.             data[i] = data[i+1];
  137.         for(int i=0; i < tmp.length; i++) {          
  138.             for(int j=0; j < numCols; j++) {
  139.                 tmp[i][j] = data[i][j];
  140.                 model.setValueAt(tmp[i][j],i,j);
  141.                 }
  142.             }
  143.         data = tmp;         
  144.         numRows = data.length;
  145.         model.fireTableDataChanged();              
  146.     }
  147.  
  148.     /** Makes each column sortable.  If the user clicks on a column 
  149.       * header, the background color changes to signal its selection.
  150.       * All table data must implement the Comparable interface.  This
  151.       * method makes all columns sortable, with no way to restrict
  152.       * sorting to certain rows.
  153.       * @param selectedBackgroundColor is the Color that the header cell
  154.       * background will be set to when that column has been selected.
  155.       */                
  156.     public void setColumnsSortable(Color selectedBackgroundColor) {
  157.         columnBackgroundClickedColor = selectedBackgroundColor;
  158.         JTableHeader header = getTableHeader();
  159.         header.setUpdateTableInRealTime(true);
  160.         header.addMouseListener(new MyColumnListener());    
  161.     }
  162.  
  163.     public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
  164.         Component c = super.prepareRenderer(renderer,row,col);
  165.         if((row&1) == 0)
  166.             c.setBackground(firstRowColor);
  167.         else
  168.             c.setBackground(secondRowColor);
  169.         return c;
  170.     }
  171.  
  172.     public void sortColumn(int whichOne) {
  173.         columnToSort = whichOne;
  174.         sortData();
  175.         MyTableModel model = (MyTableModel) getModel();
  176.         for(int i=0; i < data.length; i++)
  177.             for(int j=0; j < numCols; j++) 
  178.                 model.setValueAt(data[i][j],i,j);
  179.         repaint();
  180.         }
  181.  
  182.     private void sortData() {                          
  183.         Vector v = new Vector();                                       
  184.         for(int i=0; i < data.length; i++)                             
  185.             v.add(data[i]);                                            
  186.         Collections.sort(v, new DataComparator());                     
  187.         for(int i=0; i < data.length; i++)                             
  188.             data[i] = (Object []) v.elementAt(i);                      
  189.     }                                                                  
  190.  
  191.     class DataComparator implements Comparator {                       
  192.         public int compare(Object o1, Object o2) {                     
  193.             Object[] s1 = (Object []) o1;                              
  194.             Object[] s2 = (Object []) o2;                              
  195.             return ((Comparable)s1[columnToSort]).compareTo(s2[columnToSort]);
  196.         }                                                                   
  197.     }                                                                     
  198.  
  199. ///////////////////////////////////////////////////////////////////        
  200.     public class MyTableModel extends AbstractTableModel {        
  201.         public MyTableModel() {
  202.             }
  203.  
  204.         public String getColumnName(int col) {
  205.             return (String) colNames[col];
  206.             }
  207.  
  208.         public boolean isCellEditable(int row, int col) {
  209.             return false;
  210.             }
  211.  
  212.         public void setValueAt(Object value, int row, int col) {
  213.             data[row][col] = value;
  214.             fireTableDataChanged();            
  215.             repaint();
  216.  
  217.             fireTableCellUpdated(row,col);
  218.             }           
  219.  
  220.         public Object getValueAt(int row, int col) {
  221.             return data[row][col];
  222.             }
  223.  
  224.         public int getColumnCount() {
  225.             return colNames.length;
  226.             }
  227.  
  228.         public int getRowCount() {
  229.             return data.length;
  230.             }
  231.  
  232.         }
  233. /////////////////////////////////////////////////////////////////////////               
  234.  
  235.     public class MyColumnListener extends MouseAdapter {
  236.         private TableCellRenderer r ;
  237.         private int lastIndexSet = -1;
  238.  
  239.         public MyColumnListener() {
  240.            TableColumnModel columnModel = getColumnModel();           
  241.            TableColumn column = columnModel.getColumn(0);
  242.            r = column.getHeaderRenderer(); 
  243.            }       
  244.  
  245.         public void mouseClicked(MouseEvent e) {
  246.             JTableHeader header = parentReference.getTableHeader();          
  247.             TableColumnModel columnModel = parentReference.getColumnModel();;
  248.  
  249.             int columnModelIndex = columnModel.getColumnIndexAtX(e.getX());
  250.             int modelIndex = 
  251.                 columnModel.getColumn(columnModelIndex).getModelIndex();
  252.  
  253.             if(modelIndex < 0) return;
  254.             parentReference.sortColumn(modelIndex);
  255.             TableColumn column = columnModel.getColumn(modelIndex);
  256.             column.setHeaderRenderer(new MyCheckedHeaderRenderer());
  257.             if(lastIndexSet != -1 && lastIndexSet != modelIndex) {
  258.                 column = columnModel.getColumn(lastIndexSet);
  259.                 column.setHeaderRenderer(r);
  260.                 }
  261.             lastIndexSet = modelIndex;            
  262.             MyTableModel model = (MyTableModel) parentReference.getModel();
  263.             model.fireTableDataChanged();                             
  264.                 }                                                
  265.         }
  266.  
  267.     public class MyCheckedHeaderRenderer extends DefaultTableCellRenderer {
  268.         public Component getTableCellRendererComponent(JTable table, Object value,
  269.                                                          boolean isSelected, boolean hasFocus, int row, int column) {
  270.                 JLabel l = new JLabel(((String)value), SwingConstants.CENTER);
  271.                 l.setOpaque(true);
  272.                 l.setBackground(columnBackgroundClickedColor);
  273.                 if(headerFont != null)
  274.                     l.setFont(headerFont);
  275.                 return l;                                                        
  276.  
  277.                 }
  278.             }
  279.  
  280.  
  281.  
  282. ////////////////////////////////////////////////////////////////////////                
  283.     }


Expand|Select|Wrap|Line Numbers
  1. /*  PersistentStorage.java
  2.     A class that hold data, and keeps it persistent by syncing the
  3.     data in memory with a disk file.
  4.  
  5.     Everything passed to this class for storage must implement Serializable.
  6.  
  7.     This class is a Dictionary that uses KEY=VALUE pairs.  The class does 
  8.     not accept duplicate entries.  
  9.  
  10.     Parameterized types are used for type safety.  The Object iostreams
  11.     do not support parameterized types, so expect a class cast warning.
  12.  
  13.     Alan Riggins
  14.     CS551, Summer 09
  15. */    
  16.  
  17. import java.util.*;
  18. import java.io.*;
  19.  
  20. public class PersistentStorage<K,V> {
  21.     private TreeMap<K,V> map;
  22.     private final String filename = "persistent_data.dat";
  23.  
  24.     public PersistentStorage() {
  25.         try {            
  26.             readMapFromDisk();
  27.             }
  28.         catch(Exception e) {
  29.             map = new TreeMap<K,V>();
  30.             }
  31.         }
  32.  
  33.     // Inserts the given KEY=VALUE pair in the dictionary, and returns
  34.     // TRUE on success.  If the KEY is a duplicate, the method takes
  35.     // no action and returns FALSE.    
  36.     public boolean insert(K key, V value) {
  37.         if(map.containsKey(key))
  38.             return false;
  39.         map.put(key,value);
  40.         writeMapToDisk();
  41.         return true;
  42.         }        
  43.  
  44.     // WARNING:  The user may use the returned Object reference to
  45.     // modify either the key or value.  In such cases, the saveState()
  46.     // method must be called to insure the data on disk is in sync. 
  47.     // returns the VALUE associated with the KEY, null if the KEY is
  48.     // not in the map.    
  49.     public V getValue(K key) {
  50.         return map.get(key);
  51.         }
  52.  
  53.     public boolean containsKey(K key) {
  54.         return map.containsKey(key);
  55.         }
  56.  
  57.     public int size() {
  58.         return map.size();
  59.         }
  60.  
  61.     // Removes the KEY=VALUE pair associated with the KEY and returns
  62.     // TRUE if it is found and removed, otherwise returns FALSE.        
  63.     public boolean remove(K key) { 
  64.         if(map.remove(key) == null)
  65.             return false;
  66.         writeMapToDisk();
  67.         return true;
  68.         }                     
  69.  
  70.     public void makeEmpty() {
  71.         map.clear();
  72.         writeMapToDisk();
  73.         }
  74.  
  75.     // After an edit, you must save state to disk        
  76.     public void saveState() {
  77.         writeMapToDisk();
  78.         } 
  79.  
  80.     private void writeMapToDisk() {
  81.         try {
  82.             ObjectOutputStream out = new ObjectOutputStream(
  83.                 new BufferedOutputStream(
  84.                     new FileOutputStream(filename)));
  85.             out.writeObject(map);
  86.             out.close();
  87.             }
  88.         catch(Exception e) {
  89.             throw new RuntimeException("Error, cannot write data to disk.");
  90.             }
  91.         }
  92.  
  93.     private void readMapFromDisk() { 
  94.         try {                   
  95.             ObjectInputStream in = new ObjectInputStream
  96.                 (new BufferedInputStream
  97.                     (new FileInputStream
  98.                         (filename)));
  99.             map = (TreeMap<K,V>) in.readObject();
  100.             in.close();
  101.             }
  102.         catch(Exception e) {
  103.             throw new RuntimeException("Error, cannot read data from disk.");
  104.             }
  105.         }
  106.  
  107. ///////////////////////////////////////////////////////////////////////////
  108. //  The iterators return KEYS in sorted order as defined by Comparable<K>
  109. //  for the KEYS.  VALUES are returned in KEY sorted order.
  110.  
  111.     public Iterator<K> keys() {
  112.         return map.keySet().iterator();
  113.         }
  114.  
  115.     public Iterator<V> values() {
  116.         return map.values().iterator();
  117.         }
  118.  
  119. ///////////////////////////////////////////////////////////////////////////                
  120.     } // end class
  121.  
  122.  
Aug 9 '09 #1
Share this Question
Share on Google+
2 Replies


Expert 10K+
P: 11,448
@yeshello54
I didn't read all your code; it is way too much, but that error message tells me (and should tell you) that an array of length 6 was used and you tried to do something with an element with index 6 (the seventh element). It doesn't exist and that's why the exception was thrown.

kind regards,

Jos
Aug 10 '09 #2

P: 54
ahh yes i figured it out. Thanks.!
Aug 10 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.