javaswingnullpointerexceptionjtabledefaulttablemodel

DefaultTableModel nullpointerexception


I have a nullpointerexception and the problem comes from the defaulttablemodel tabel1, does anyone know what the problem is?((main))

package tafel.van.pkg7;
import javax.swing.*;

public class TafelVan7 extends JFrame {

    public static void main(String[] args) {
       JFrame frame = new TafelVan7();
        frame.setSize( 500,800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle ("quizvragen");
        frame.setContentPane( new paneel());
        frame.setVisible( true ); 
    }
}

((Panel)) This is the panel with an array and a table, the row gets added in the for-loop

package tafel.van.pkg7;

import java.awt.Color;
import javax.swing.*;
import javax.swing.table.*;



class paneel extends JPanel {
    public static JTable tabel;
    public JScrollPane scroll;
    static int product = 7;
    int uitkomst; 

    public paneel(){
        Object[] Kolom = {"7", "tafel van 7"};
        TableModel model = new DefaultTableModel(Kolom,0);
        DefaultTableModel tabel1 = (DefaultTableModel) tabel.getModel();

        tabel = new JTable(model);
        JTableHeader hoofd = tabel.getTableHeader();
        hoofd.setBackground(Color.BLACK);
        hoofd.setForeground(Color.WHITE);

        scroll = new JScrollPane(tabel);
        tabel.setFocusable(false);
        tabel.setRowSelectionAllowed(false);
        this.add(scroll);



        int row = 1;
        for(int x=1; x<=100;x++){
            Integer[] product = new Integer[2];
            product[0]= x;
            product[1]= x*7;
            tabel1.addRow(product);

((full error))

run:
Exception in thread "main" java.lang.NullPointerException
    at tafel.van.pkg7.paneel.<init>(paneel.java:19)
    at tafel.van.pkg7.TafelVan7.main(TafelVan7.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Solution

  • I found the mistake, The defaulttablemodel is on the wrong place this is how it should be:

    (part of panel)

    scroll = new JScrollPane(tabel);
            tabel.setFocusable(false);
            tabel.setRowSelectionAllowed(false);
            this.add(scroll);
    
            DefaultTableModel tabel1 = (DefaultTableModel) tabel.getModel();
    
            int row = 1;
            for(int x=1; x<=100;x++){
                Integer[] product = new Integer[2];
                product[0]= x;
                product[1]= x*7;
                tabel1.addRow(product);