Solved

Null Pointer in JTable Model

Posted on 1999-01-27
2
400 Views
Last Modified: 2008-03-17
I get a Null Pointer Exception when I try to run the following code.  The String[][] is not null when the constructor for the model is formed.
getRowCount() is called by the table the data is then Null
The output and a small section of the stack trace is below:
Data Values: 1-1
Data Values: 2-1
Data Values: 3-1
LEN: 3
java.lang.NullPointerException:
      at TableTry$GraphTableModel.getRowCount(TableTry.java:130)
      at javax.swing.JTable.getRowCount(JTable.java:1360)

//TableTry.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.io.*;

public class TableTry extends JPanel {
      String heading[];
      Button cancel;
      String newline;
      Vector vect;
     int marker=0;

      public TableTry(Vector vect) {

            this.vect= vect;
            this.setLayout(new BorderLayout(20,20));
            this.setBackground(Color.lightGray);
            JPanel head= new JPanel();
            head.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
          head.setBackground(Color.lightGray);
          this.add("North",head);
            head.setFont(new Font("SansSerif",Font.BOLD,20));
            heading=(String[]) vect.elementAt(0);
            head.add(new JLabel(heading[0]));

            JPanel body= new JPanel();
            body.setLayout(new FlowLayout(FlowLayout.CENTER));
         
            GraphTableModel gtm= new GraphTableModel();
            JTable table= new JTable(gtm);
          initColumnSizes(table, gtm);                            //initializes the column sizes

          table.setPreferredScrollableViewportSize(new Dimension(500,100));
         
          JScrollPane scrollPane = new JScrollPane(table);
          body.add(scrollPane);
            this.add(BorderLayout.CENTER,body);            
      }
     
     private void initColumnSizes(JTable table, GraphTableModel model) {

        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;

        for (int i = 0; i < table.getColumnCount(); i++) {
            column = table.getColumnModel().getColumn(i);

            comp = column.getHeaderRenderer().getTableCellRendererComponent(null, column.getHeaderValue(),false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i],false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }
     
     /**
     Main method used for testing purposes only
     Creates a Frame and uses sample data from a file
     in the current directory named "1099wmac.dat"
     */
     
     public static void main(String s[])  {
         
          //TEMP
          Vector vect= new Vector();
          String[] temp1= {"Heading"};
          String[] temp2= {"first","second","third","fourth","fifth","sixth","seventh","eighth"};
          String[] temp3= {"1-1","1-2","1-3","1-4","1-5","1-6","1-7","1-8"};
          String[] temp4= {"2-1","2-2","2-3","2-4","2-5","2-6","2-7","2-8"};
          String[] temp5= {"3-1","3-2","3-3","3-4","3-5","3-6","3-7","3-8"};
          vect.addElement(temp1);
          vect.addElement(temp2);
          vect.addElement(temp3);
          vect.addElement(temp4);
          vect.addElement(temp5);
         
          JFrame f= new JFrame("Test");
          //FileData vals= new FileData();
          //try  {
          //     f.getContentPane().add(new TableTry(vals.getGrafData("1099wmac.dat")));
          //}
          //catch(IOException e)  {
          //     System.out.println("IO Problem");
          //}
          f.getContentPane().add(new TableTry(vect));
         
          f.addWindowListener(new WindowAdapter()  {
               public void windowClosing(WindowEvent e)  {
                    System.exit(0);
               }
          });
          f.setSize(800,600);
          f.setVisible(true);
     }

     
     /**Table Model class -- defines the table data and column info
     */
     
     class GraphTableModel extends AbstractTableModel {
          String[] columnNames;
          String[][] data;
          String[] longValues= {"first","second","third","fourth","fifth","sixth","seventh","eighth"};
         
          GraphTableModel()  {
         
               columnNames = (String[])vect.elementAt(1);
               String[][] data= new String[vect.size()-2][];
               for (int i=2;i<vect.size();i++)  {
                    if (vect.elementAt(i) == null) break;
                    data[i-2]= (String[])vect.elementAt(i);
                    System.out.println("Data Values: " + data[i-2][0]);
               }
               System.out.println("LEN: " + data.length);
               //need to actually calculate the long values but for now use test data
          }
          public int getColumnCount() {
               return columnNames.length;
          }
          public int getRowCount() {
               //System.out.println("In getRowCount(): " + data.length);   //data is NULL -- why??
               return data.length;
          }
          public String getColumnName(int col) {
               return columnNames[col];
          }
          public Object getValueAt(int row, int col) {
               return data[row][col];
          }
     }
}
0
Comment
Question by:mbunkows
2 Comments
 

Accepted Solution

by:
ssbera earned 70 total points
Comment Utility
Hi mbunkows,

See constructor of the class GraphTableModel ie
GraphTableModel()  {
               
                   columnNames = (String[])vect.elementAt(1);
                   String[][] data= new String[vect.size()-2][];
                   for (int i=2;i<vect.size();i++)  {
                        if (vect.elementAt(i) == null) break;
                        data[i-2]= (String[])vect.elementAt(i);
                        System.out.println("Data Values: " + data[i-2][0]);
                   }

here data is local variable. If you see in your code ...
String[][] data is attribute of the class . so data is global for the class. but in constrctor you have declared data again. So constructor code should be like this..

GraphTableModel()  {
               
                   columnNames = (String[])vect.elementAt(1);
                   // delete String[][]   from     String[][] data= new String[vect.size()-2][];
                   data= new String[vect.size()-2][];
                   for (int i=2;i<vect.size();i++)  {
                        if (vect.elementAt(i) == null) break;
                        data[i-2]= (String[])vect.elementAt(i);
                        System.out.println("Data Values: " + data[i-2][0]);
                   }


0
 

Author Comment

by:mbunkows
Comment Utility
Thats the SECOND time Ive let that stump me.
I'll learn I guess
Thanks!

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now