2017-05-29 64 views
1

我在Netbeans中使用Swings。我已經創建了名爲「view」的按鈕,當我單擊view按鈕時,它應該獲取數據庫表並在同一頁上顯示查看按鈕下方的表。netbeans中的Swing table view

我的代碼:

private void viewActionPerformed(java.awt.event.ActionEvent evt) {          
    showData(); }          


public void showData() 
    { 
     Connection con=null; 
     Statement st=null; 
     ResultSet rs=null; 
     String s; 
     try 
     { 
      con=DriverManager.getConnection("jdbc:mysql://localhost/testm","root","root"); 
      st=con.createStatement(); 
      s="select * from smpl"; 
      rs=st.executeQuery(s); 


     ResultSetMetaData rsmt= rs.getMetaData(); 
     int c=rsmt.getColumnCount(); 
     Vector column=new Vector(c); 
     for(int i=1;i<=c;i++) 
     { 

     column.add(rsmt.getColumnName(i)); 
     } 
     Vector data= new Vector(); 
     Vector row= new Vector(); 
     while(rs.next()) 
     { 
     row=new Vector(c); 
     for(int i=1;i<=c;i++) 
     { 
      row.add(rs.getString(i)); 
     } 
     data.add(row); 
     } 

    JFrame smp=new JFrame(); 
    smp.setSize(1000,500); 
    // smp.setLocation(0, 300); 
    //smp.setUndecorated(true); 
     smp.setLocationRelativeTo(null); 
     smp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel=new JPanel(); 
     // paneldes.setLocation(20, 100); 
     JTable table= new JTable(data,column); 
     JScrollPane jsp= new JScrollPane(table); 

     panel.setLayout(new BorderLayout()); 
     //paneldes.setLocation(100, 200); 
     panel.add(jsp,BorderLayout.CENTER);  
     // paneldes.add(jsp); 
     // jsp.setLocation(100, 200); 
     this.setContentPane(panel); 
     this.setVisible(true); 
     SwingUtilities.getAncestorOfClass(null, jsp); 
    } 

     catch(Exception e) 
       {JOptionPane.showMessageDialog(null,"ERROR"); 
       }finally{ 
         try{ 
         st.close(); 
         rs.close(); 
         con.close(); 
         }catch(Exception e){ 
         JOptionPane.showMessageDialog(null,"ERROR CLOSE"); 

       }}} 
public static void main(String args[]) { 
java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new smplvi().setVisible(true); 
      } 
     }); 
    } 

在此先感謝

+0

這是什麼目前做什麼? – Shane

+0

它顯示錶格上方的結果 –

+0

也許你應該從[如何使用表格](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) – MadProgrammer

回答

0

嘗試做這樣的,不與載體

 DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); 
    String data1 = something1.columnOneFromDB; 
    String data2 = something2.columnTwoFromDB; 
    String data3 = something3.columnThreeFromDB(); 
    String data4 = something4.columnFourFromDB(); 

    Object[] row = { data1, data2, data3, data4 }; 

    model.addRow(row); 
+0

開始謝謝你爲我工作 –