Jtable - Nullpointerexception when I addRow() in jTable from another class

Asked

Viewed 25 times

0

I wanted to know what solution to be able to add to jTable lines so as not to give me Nullpointerexception

public class Estatistica extends javax.swing.JFrame {



public static DefaultTableModel model;

/**
 * Creates new form Estatistica
 */
public Estatistica() {
    initComponents();
    model = (DefaultTableModel) jTable1.getModel();

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    jLabel1.setText("Informação");

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "Nome", "Idade", "Data"
        }
    ));
    jScrollPane1.setViewportView(jTable1);  (....)

But when in the other class I ask to insert a row in the table

public class II {

/**
 * @param args the command line arguments
 */

public static void main(String[] args) {
    // TODO code application logic here

  // Estatisticas.mode.addRow(new Object[]{"ol23", "ola", "ola"});
 Estatistica.model.addRow(new Object[]{"ol23", "ola", "ola"});}

It always gives me the error of Exception in thread "main" java.lang.Nullpointerexception

What a solution I have for this?

1 answer

0


You missed instantiating the Statistic object, using the reserved word "new":

    public class II {

    /**
    * @param args the command line arguments
    */

    public static void main(String[] args) {
       // TODO code application logic here

       // Estatisticas.mode.addRow(new Object[]{"ol23", "ola", "ola"});
       new Estatistica().model.addRow(new Object[]{"ol23", "ola", "ola"});}

Nullpointerexception in your code was released when you tried to call a method in a null object.

  • Right! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.