Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Null Pointer in JTable Model

Posted on 1999-01-27
2
Medium Priority
?
410 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 

Accepted Solution

by:
ssbera earned 280 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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

721 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