Solved

Null Pointer in JTable Model

Posted on 1999-01-27
2
401 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
ID: 1234806
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
ID: 1234807
Thats the SECOND time Ive let that stump me.
I'll learn I guess
Thanks!

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
basic hardware to learn oop advanced design patterns 3 88
starter POM and spring-boot-starter,  spring-boot-web 2 43
eclipse argument 14 53
expectj telnet failing 5 26
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

862 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

26 Experts available now in Live!

Get 1:1 Help Now