title: Can not display JTable in JFrame at button click
body: <p>I am trying to add JTable at run time at click of a button(SEARCH button) in my application. The table was successfully displayed in a different program but when I tried to add code in actionPerformed method of the button here, the JTable is not displayed.</p>
  
  <p>The GUI was created using netbeans GUI but I moved it to eclipse and adding the code for database.</p>
  
  <p>The JTable displays data from database. The data is retrieved at button click. And the JTable should be displayed only at the button click containing that data on the same frame just below the buttons  </p>
  
  <p>The only issue is of JTable not being displayed. I tried using JScrollPane along with JPanel with no success. Tried other ways as well.</p>
  
  <pre><code> '        
  
   package lib_ss;
  
   import java.awt.BorderLayout;
   import java.awt.Font;
   import java.sql.Connection;
   import java.sql.DriverManager;
   import java.sql.PreparedStatement;
   import java.sql.ResultSet;
   import java.util.ArrayList;
  
   import javax.swing.JPanel;
   import javax.swing.JScrollPane;
   import javax.swing.JTable;
   import javax.swing.SwingConstants;
   import javax.swing.table.DefaultTableCellRenderer;
   import javax.swing.table.DefaultTableModel;
   import javax.swing.table.TableColumn;
  
  
   public class NewJFrame2 extends javax.swing.JFrame {
  
      public int id=0;
  
      public void getId(int i)
      {
          id=i;
  
      }
  
  
     JScrollPane  pane;
  
     TableColumn column;
  
     ResultSet rs=null;
  
     String col[]={"ID","NAME","AUTHOR","DEPT","Location","Publisher","Edition"};
  
     ArrayList&lt;String[]&gt; values = new ArrayList&lt;&gt;();
  
     DefaultTableModel model;
  
    JTable table;
    int k=0;
    private Connection con;
  
     public void connect()
     {
  
      try {
          Class.forName("oracle.jdbc.OracleDriver");
          con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","system","manhattan");
      } catch (Exception e) 
      {
          e.printStackTrace();
      }
     }
  
  /**
   * Creates new form NewJFrame2
   */
  public NewJFrame2() {
      initComponents();
  
  
         }
  
  NewJFrame2(NewJFrame1 aThis) {
      throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  }
  
  
  
  /**
   * 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")
  // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt;//GEN-BEGIN:initComponents
      public void initComponents() {
  
      buttonGroup1 = new javax.swing.ButtonGroup();
      buttonGroup2 = new javax.swing.ButtonGroup();
      jButton1 = new javax.swing.JButton();
      jButton2 = new javax.swing.JButton();
      jButton3 = new javax.swing.JButton();
      jLabel1 = new javax.swing.JLabel();
  
  
  
  
  
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
  
      jButton1.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
      jButton1.setText("Log Out");
      jButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton1ActionPerformed(evt);
          }
          });
      getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1060, 50, -1, -1));
  
      jButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
      jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib_ss/mic1.png"))); // NOI18N
      jButton2.setText("Search");
      jButton2.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton2ActionPerformed(evt);
          }
          });
      getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(619, 124, -1, -1));
  
      jButton3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
      jButton3.setText("Previous Records");
      jButton3.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton3ActionPerformed(evt);
          }
          });
      getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 124, 203, 56));
  
      jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib_ss/url1.jpg"))); // NOI18N
      jLabel1.setText("jLabel1");
      getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1230, 740));
  
      pack();
      }// &lt;/editor-fold&gt;//GEN-END:initComponents
  
  public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
      // TODO add your handling code here:
      NewJFrame1 frame = new NewJFrame1();
  
      frame.setVisible(true);
      this.dispose();
  }//GEN-LAST:event_jButton1ActionPerformed
  
  
  
  public void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
   {
  
      try {
          Class.forName("oracle.jdbc.OracleDriver");
          con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","system","manhattan");
  
     PreparedStatement ps=con.prepareStatement("select * from records where    stid=?");
  
       ps.setInt(6,id);
  
     //ps.setString(2,"bruce");
  
  
  
       rs=ps.executeQuery();
  
       if (rs.next()) 
  
         {            }
  
  
        }
      catch(Exception e)
        {
          e.printStackTrace();
              }
           }
  
  
  
     //Search Button
     public void jButton2ActionPerformed(java.awt.event.ActionEvent evt) 
      {
               int i=0;
  
  
                  try {
                  Class.forName("oracle.jdbc.OracleDriver");
                  con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","system","manhattan");
  
              PreparedStatement ps=con.prepareStatement("select * from books where name=? or author=?");
  
          ps.setString(1,"java");
            ps.setString(2,"bruce");
            rs=ps.executeQuery();
  
  
  
           /* for (int l = 0; l &lt; 7; l++) {
                column = table.getColumnModel().getColumn(l);
  
                if (l==0) {
                    column.setPreferredWidth(25); 
                }
                if (l == 1||l==2) {
                    column.setPreferredWidth(90); 
                }
                if (l == 3||l==5) {
                    column.setPreferredWidth(145); 
                } 
  
                if(l==4||l==6) {
                    column.setPreferredWidth(87);
                }
               }
            */
  
            /*model = new DefaultTableModel(col,7);
            DefaultTableCellRenderer rightRenderer = new  DefaultTableCellRenderer();
          rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
  
  
  
              while (rs.next()) 
  
              {           
              String arr[] ={Integer.toString(rs.getInt("ID")),
              rs.getString("NAME"),rs.getString("AUTHOR"),
              rs.getString("DEPT"),rs.getString("LOC"),
              rs.getString("PUBLISHER"),rs.getString("EDITION")};
  
              table.setFont(new Font("Serif", Font.PLAIN, 20));
  
                      for(int j=0;j&lt;7;j++)
                         {                        
                          if(k&lt;arr.length&amp;&amp;i&lt;10)      
                  {table.setValueAt(arr[k],i,j);
                   table.getColumnModel().getColumn(j).setCellRenderer(rightRenderer);
                      k++;
                      }   
                              }
                      i++;    }
                                  */
  
  
               while (rs.next()) {
                  String arr[] ={
                    Integer.toString(rs.getInt("ID")),
                    rs.getString("NAME"),rs.getString("AUTHOR"),
                    rs.getString("DEPT"),rs.getString("LOC"),
                    rs.getString("PUBLISHER"),rs.getString("EDITION")
                };
                values.add(arr);
                 }
  
  
  
  
            String[][] data = values.toArray(new String[values.size()][]);
            model = new DefaultTableModel(data,col);
            table.setModel(model);
  
  
                    /*   if(rs.next())
                         {
                          String msg = "BOOK FOUND";
                          JLabel label = new JLabel(msg);
                          label.setFont(new Font("serif", Font.PLAIN, 18));
                          JOptionPane.showMessageDialog(null, label);
                         }
                        else
                        {String msg = "BOOK NOT FOUND";
                      JLabel label = new JLabel(msg);
                      label.setFont(new Font("serif", Font.PLAIN, 18));
                      JOptionPane.showMessageDialog(null, label);}
                      */
  
  
  
  
            System.out.println("hello");
  
  
       //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)   
  
  
                          /*
              JScrollPane scroll=new JScrollPane(table);
              //JPanel panel=new JPanel();
              //panel.add(scroll);
              //getContentPane().add(scroll,BorderLayout.CENTER);
              */
  
  
  
              JScrollPane scroll=new JScrollPane(table);
              JPanel panel=new JPanel();
              panel.add(scroll);
              getContentPane().add(panel);
  
              revalidate();
              repaint();
  
  
              //JScrollPane scroll=new JScrollPane(table);
  
               /*
              JPanel p=new JPanel();
              p.add(table);
              add(p);
            */
  
          //table.setBounds(200,200,100,100);
          //table.setLocation(200,200);
          //setVisible(true);
          //setSize(900,900);
          //getContentPane().add(pane);
          //setLayout(new FlowLayout());
          //setDefaultCloseOperation(EXIT_ON_CLOSE);
              }
  
                  catch (Exception e) 
              {
                  e.printStackTrace();
              }
  
  
  
  }//GEN-LAST:event_jButton2ActionPerformed
  
  
  
  public static void main(String args[]) {
        /* Set the Nimbus look and feel */
      //&lt;editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "&gt;
      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
       * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
         try {
          for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
              if ("Nimbus".equals(info.getName())) {
                  javax.swing.UIManager.setLookAndFeel(info.getClassName());
                  break;
              }
          }
        } catch (ClassNotFoundException ex) {
          java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (InstantiationException ex) {
          java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
          java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
          java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      //&lt;/editor-fold&gt;
  
      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
          @Override
          public void run() {
              new NewJFrame2().setVisible(true);
          }
      });
    }
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.ButtonGroup buttonGroup1;
  private javax.swing.ButtonGroup buttonGroup2;
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JButton jButton3;
  private javax.swing.JLabel jLabel1;
  // End of variables declaration//GEN-END:variables
   }
  </code></pre>
  
  <p>Here is the error:</p>
  
  <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
  at javax.swing.ImageIcon.&lt;init&gt;(ImageIcon.java:217)
  at lib_ss.NewJFrame2.initComponents(NewJFrame2.java:128)
  at lib_ss.NewJFrame2.&lt;init&gt;(NewJFrame2.java:64)
  at lib_ss.NewJFrame2$4.run(NewJFrame2.java:364)
  at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:749)
  at java.awt.EventQueue.access$500(EventQueue.java:97)
  at java.awt.EventQueue$3.run(EventQueue.java:702)
  at java.awt.EventQueue$3.run(EventQueue.java:696)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:719)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
  </code></pre>