2013-06-29 71 views
3

在我的程序中,我創建了一個包含名爲jp的JPanel的JFrame。 jp還包含一個我想填充一些行的JTable。在JPanel中創建JTable並添加行

case KeyEvent.VK_R: 
    JFrame frame = new JFrame("Snake v2.0 - Rankings"); 
    JPanel jp = new JPanel(); 
    jp.setPreferredSize(new Dimension(300,300)); 

    JTable table = new JTable(); 
    JScrollPane tableContainer = new JScrollPane(table); 
    jp.add(tableContainer, BorderLayout.CENTER); 
    DefaultTableModel tm = (DefaultTableModel) table.getModel(); 
    tm.addRow(new Object[] {"#","Player","Score","Date"}); 

    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 
    frame.setResizable(false); 
    frame.getContentPane().add(jp); 
    frame.pack(); 
    frame.setVisible(true); 
break; 

這是我的代碼。當我按下鍵盤上的R時,出現了帶有該JPanel的JFrame,但表格沒有(picture)。我能做什麼?

回答

8

第一件事情是你沒有添加的列名到表。

改變這種

DefaultTableModel tm = (DefaultTableModel) table.getModel(); 
tm.addRow(new Object[] {"#","Player","Score","Date"}); 

編輯

DefaultTableModel tm = new DefaultTableModel(new Object[] {"#","Player","Score","Date"},0); 
table.setModel(tm); 

,並添加一行

tm.addRow(new Object[]{1,"XXX","99","2013-06-29"}); 
+2

你的代碼的工作,謝謝:) –

+1

oohh ..看到更新.. –

+1

是啊,我自己修復它;) –

3

//設置表和滾動條的JPanel

DefaultTableModel table_model = new DefaultTableModel(addressData, new String[]{"First Name", "Surname", "Home Number", "Mobile Number", "Address", "Postcode"}); 
JTable table = new JTable(this.table_model); 
table.setBounds(130, 40, 200, 200); 
jp.add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));