点击按钮

时间:2015-05-09 13:39:30

标签: java swing jtable

我试图在运行时通过单击应用程序中的按钮(SEARCH按钮)添加JTable。该表已成功显示在另一个程序中,但是当我尝试在此处按钮的actionPerformed方法中添加代码时,不会显示JTable。

GUI是使用netbeans GUI创建的,但我将其移至eclipse并添加了数据库代码。

JTable显示数据库中的数据。按钮单击时检索数据。并且JTable应仅在按钮单击时显示,该按钮单击包含按钮

下方同一帧上的数据

唯一的问题是JTable没有显示。我尝试使用JScrollPane和JPanel但没有成功。尝试其他方式。

 '        

 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<String[]> values = new ArrayList<>();

   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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//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();
    }// </editor-fold>//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 < 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<7;j++)
                       {                        
                        if(k<arr.length&&i<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 */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* 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);
    }
    //</editor-fold>

    /* 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
 }

这是错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at lib_ss.NewJFrame2.initComponents(NewJFrame2.java:128)
at lib_ss.NewJFrame2.<init>(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)

3 个答案:

答案 0 :(得分:0)

我在我的应用程序中做了同样的事情。

我做的是,我在主面板上添加了JPanel,然后使用Netbeans GUI在该面板上添加了JTable

最初,使用JPanel隐藏包含您的桌子的JPanel.setVisible(false); ..这样它就不会显示,直到按下该按钮。

在按钮actionPerformed中编写如下代码: 假设您的JPanel名称为“小组”,JTable名称为“标签”

panel.setVisible(true);
DefaultTableModel model= (DefaultTableModel) tab.getModel();

        //your code to get data from database

        while (rs.next()){
            Object rowData= new Object[7]; //as your table has 7 fields/columns
            rowData[0]=rs.getInt("ID");
            rowData[1]=rs.getString("NAME");
            rowData[2]=rs.getString("AUTHOR");
            rowData[3]=rs.getString("DEPT");
            rowData[4]=rs.getString("LOC");
            rowData[5]=rs.getString("PUBLISHER");
            rowData[6]=rs.getString("EDITION");
         }
         model.addRow(rowData);

根据您的需要修改此代码......它有效。

答案 1 :(得分:0)

我的建议是:

    //getContentPane().add(scroll,BorderLayout.CENTER);

您添加以下行:

    revalidate();
    repaint();

也替换

            /*
            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);

新异常后编辑

您的主要问题在于方法javax.swing.JTable.setValueAt(JTable.java:2742)中的这一行jButton2ActionPerformed。研究你的代码我发现初始化DefaultTableModel你使用了以下行:

model = new DefaultTableModel(col,10); 

在这里,我找不到变量col在您上传的代码中的初始化位置。我觉得col可能已初始化为0。因此,如果col值为0,则DefaultTableModel将包含0列,因此当您尝试向其添加数据时,ArrayIndexOutOfBoundsException会发生此异常。您还指定了表的行数为10。如果ArrayIndexOutOfBoundsException返回超过10行,则会再次出现ResultSet

我建议您在收集DefaultTableModel对象中的所有数据后初始化ResultSet,如下所示:

  1. 首先,在ArrayList循环检索来自您values实例的数据之前,声明并初始化String[] while类型rs,如图所示下面:

          ArrayList<String[]> values = new ArrayList<>();
    
  2. while循环中检索来自rs对象的数据,而不是使用table将数据添加到setValueAt变量,将数据添加到ArrayList {1}}对象values如下图所示:

          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);
          }
    
  3. 创建一个新的String[]变量,说columnNames来存储列的名称。这些名称将显示为表格标题中列的名称,如下所示:

          String[] columnNames = {
                  "ID","NAME","AUTHOR",
                  "DEPT","LOC",
                  "PUBLISHER","EDITION"
          };
    
  4. 现在使用构造函数DefaultTableModel初始化model变量DefaultTableModel(Object[][] data,Object[] columnNames)。当我们调用基本上属于data类型的values.toArray()时,我们会收到String[][]。这说明如下:

          String[][] data = values.toArray(new String[values.size()][]);
          model = new DefaultTableModel(data,columnNames);
    
  5. 最后将model变量设置为ModelJTable,如图所示。

          table.setModel(model);
    
  6. 由于您的初始代码,上面的建议不仅会处理ArrayIndexOutOfBoundsException,还会处理如果rs对象返回的行数超过10的事实。希望这能解决你目前的问题。

    您的完整代码

    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 java.awt.Dimension;
    
    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;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    
    public class NewJFrame2 extends javax.swing.JFrame {
    
        String[] col={"ID","NAME","AUTHOR","DEPT","Location","Publisher","Edition"};
        private Connection con;
    
        public int id=0;
    
        public void getId(int i){
            id=i;
        }   
        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")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
        public void initComponents() {
    
            JButton jButton1 = new JButton();
            JButton jButton2 = new JButton();
            JButton jButton3 = new JButton();
            JLabel jLabel1 = new JLabel();
    
            getContentPane().setLayout(new java.awt.FlowLayout());
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            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);
    
    
            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);
                }
            });
            jButton2.setVisible(true);
            getContentPane().add(jButton2);
    
    
            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);
    
    
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib_ss/url1.jpg"))); // NOI18N
            jLabel1.setText("jLabel1");
            getContentPane().add(jLabel1);
    
            pack();
        }// </editor-fold>//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);
    
                ResultSet rs=ps.executeQuery();
    
                if (rs.next()){
                    //TODO add functionality.
                }
    
            }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");
                ResultSet rs=ps.executeQuery();
    
                ArrayList<String[]> values = new ArrayList<>();
    
                if (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()][]);
                DefaultTableModel model = new DefaultTableModel(data,col);
                JTable table = new JTable(model);
    
    //System.out.println("hello");
    
                JScrollPane scroll=new JScrollPane(table);
                JPanel panel=new JPanel();
                panel.add(scroll);
                getContentPane().add(panel);
    
                pack();
    
            }catch (Exception e){
                e.printStackTrace();
            }
    
        }//GEN-LAST:event_jButton2ActionPerformed
    
    
        public static void main(String[] args){
            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);
            }
    //</editor-fold>
    
    /* 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
    // End of variables declaration//GEN-END:variables
    }
    

    我已经对它进行了测试,并且在没有数据库连接和图像的情况下工作正常。

答案 2 :(得分:0)

填充ArrayList

 public ArrayList<classExpens> expensList()
{
    ArrayList<classExpens> expensList = new ArrayList<classExpens> ();
    conn=mySqlConnection.ConnectDB();
    String sql="select * from tbl_name";
   try{
       Statement st = conn.createStatement();
       rs=st.executeQuery(sql);

       classExpens expens;
       while(rs.next()){
           expens = new classExpens(rs.getInt("id"),rs.getString("name"),rs.getString("item"),rs.getFloat("price"),rs.getString("date"));

           expensList.add(expens);
       }

   }
   catch(Exception ex){
       ex.printStackTrace();
   }
   return expensList;

}

从arrayList填充表

public void showTable(){
    ArrayList<classExpens> list = expensList();
   DefaultTableModel model = (DefaultTableModel)tblExpens.getModel();
   while(tblExpens.getRowCount()>0)
   {
       ((DefaultTableModel)tblExpens.getModel()).removeRow(0);
   }
   Object[]row = new Object[5];

   for (int i = 0; i <list.size(); i++) {
       row[0]=list.get(i).getid();
       row[1]=list.get(i).getname();
       row[2]=list.get(i).getitem();
       row[3]=list.get(i).getprice();
       row[4]=list.get(i).getdate();



       model.addRow(row);
   }

}

在JForm jtextFields或jlabels中显示数据

public void showItems(int index){
    lblid.setText(Integer.toString(expensList().get(index).getid()));
    txtName.setText(expensList().get(index).getname());
    txtItem.setText(expensList().get(index).getitem());
    txtprice.setText(Float.toString(expensList().get(index).getprice()));

    try{
        java.util.Date addDate= null;
        addDate = new SimpleDateFormat("yyyy-MM-dd").parse((String)expensList().get(index).getdate());
        this.Date.setDate(addDate);
    }
    catch(ParseException e){
        JOptionPane.showMessageDialog(null,"Date and Time Error");
    }
}