JTable doesn't add header row
I try to add header row to my JTable and next put table on panel.
Map <String, Float> tmpCart = new HashMap<String , Float>();
    MainPanel.removeAll();
    MainPanel.repaint();
    tmpCart = cart.GetMap();
        DefaultTableModel tab = new DefaultTableModel();
        tab.setColumnIdentifiers(new String[] {"Name", "Price"});
            for (String key : tmpCart.keySet())
            tab.addRow(new Object[] {key, tmpCart.get(key)});
        JTable jTab = new JTable(tab);
        jTab.setBounds(10, 10, 200, 200);
        jTab.setBackground(Color.orange);
        jTab.setRowHeight(25);
        JScrollPane pan =new JScrollPane(jTab);
         MainPanel.add(pan);
        // MainPanel.add(jTab);
       // pan.repaint(); 
How do I write it properly?
//answer
I try create JTable dynamically, 开发者_如何学编程after push button, I want get data from Hashtable, create table and put this table on panel.
First step is remove all components from panel, and next create JTable using data from Hashmap`
full function:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
    DefaultTableModel tab = new DefaultTableModel();
    tab.setColumnIdentifiers(new String[] {"Name", "Price"});
        for (String key : tmpCart.keySet())
        tab.addRow(new Object[] {key, tmpCart.get(key)});
    JTable jTab = new JTable(tab);
    jTab.setBounds(10, 10, 200, 200);
    jTab.setBackground(Color.orange);
    jTab.setRowHeight(25);
    // MainPanel.add(pan);
     MainPanel.add(jTab);            
}
This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price").
Can't tell exactly what you are doing from the code sample.
If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel.
table.setModel( model );
If you need more help then post your SSCCE that demonstrates the problem.
Edit:
First step is remove all components from panel,
Why are your removing components from the panel?
If you need to "swap" panels, then use a CardLayout.
If you need to "refresh" existing components, then just reset the model as explained above.
// MainPanel.add(pan);
MainPanel.add(jTab);               
The scrollPane should be added to the GUI, not the table.
The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via
new JScrollPane(table)
and add that to your MainPanel.
The other option is to added the header directly wherever you want it, and for that you can do:
panel.add(table.getTableHeader())
Try putting it into a JScrollPane.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论