在JPanel中创建JTable并添加行

时间:2013-06-29 10:11:38

标签: java swing jtable

在我的程序中,我用dinamically创建了一个包含名为jp的JPanel的JFrame。 jp还包含一个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)。我该怎么办?

2 个答案:

答案 0 :(得分: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"});

答案 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));