2014-01-11 81 views
-1

現在我只是使用JList,但它看起來好多了,如果數據顯示在JTable。 這是GUI類:使用矢量JTable

public class Table extends JFrame { 

private JPanel contentPane; 
DefaultTableModel tableModel = new DefaultTableModel(); 
private JTable table; 
private Controller controller = new Controller(); 
private static Vector <Vector<String>> data = new Vector <Vector<String>>(); 


/** 
* Launch the application. 
*/ 


public Table() throws SQLException { 

    Vector <String> columnNames = new Vector <String>(); 
    ResultSet rs2 = controller.getPerson(); 
    while (rs2.next()){ 
    columnNames.add(rs2.getString(1)); 
    } 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 450, 300); 
    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    contentPane.setLayout(new BorderLayout(0, 0)); 
    setContentPane(contentPane); 

      //add tableModel into table 
    table = new JTable(tableModel); 

    contentPane.add(table, BorderLayout.CENTER); 
      //Create JButton 
    JButton showBtn = new JButton("Show"); 
    showBtn.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      try { 
     ResultSet rs = controller.getPerson(); 
     while (rs.next()){ 
     Vector <String> vstring = new Vector <String>(); 
      vstring.add(rs.getString(1)); 
      data.add(vstring); 

       } 
      } catch (SQLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    }); 
    contentPane.add(showBtn, BorderLayout.SOUTH); 
}} 

當點擊了按鈕的數據應在JTable顯示。我真的不知道如何遍歷數據庫中的列和行,然後將此信息添加到JTable

+0

_I數據真的不知道該怎麼循環遍歷數據庫中的列和行,並且您做了**要查找的內容?有很多類似的問題(帶有很好的答案)在這個網站上... – kleopatra

回答

1

//全局聲明

private Vector<Vector<String>> data; //used for data from database 
private Vector<String> header; //used to store data header 

//顯示信息,以JTable中

data = get(); 

    //create header for the table 
    header = new Vector<String>(); 
    header.add("Column1"); 
    header.add("Column2"); 
    ... 
    model=new DefaultTableModel(data,header); 
    table = new JTable(model); 

這將幫助你從數據庫

get(){ 
Vector<Vector<String>> doublevector = new Vector<Vector<String>>(); 

Connection conn = dbConnection();//Your Database connection code 
PreparedStatement pre1 = conn.prepareStatement("select * from Table"); 

ResultSet rs1 = pre1.executeQuery(); 
while(rs1.next()) 
{ 
Vector<String> singlevector = new Vector<String>(); 
singlevector.add(rs1.getString(1)); 
singlevector.add(rs1.getString(2)); 
.... 
doublevector.add(singlevector); 

} 

return doublevector; 
}