开发者

JTable adding new row

I have a JTable with 5 rows at the time of design. Now i have to add more rows as i go dynamically. I am getting array out of bound exception error when i add more rows. How do i solve this issue ?

item_list = new javax.swing.JTable();  
item_list.setModel(new javax.sw开发者_Python百科ing.table.DefaultTableModel(  
    new Object [][] {  
        {null, null, null},  
        {null, null, null},  
        {null, null, null},  
        {null, null, null}  
    },  
    new String [] {  
        "No.", "Description", "Cost"  
    }  
) {  
    Class[] types = new Class [] {  
        java.lang.Integer.class, java.lang.String.class, java.lang.Float.class  
    };

    public Class getColumnClass(int columnIndex) {  
        return types [columnIndex];  
    }  
});  
item_list.getColumnModel().getColumn(0).setPreferredWidth(30);  
item_list.getColumnModel().getColumn(1).setPreferredWidth(100);  
item_list.getColumnModel().getColumn(2).setPreferredWidth(50);  
jScrollPane2.setViewportView(item_list);


this works for me

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

public class Grow extends JFrame {

    private static final Object[][] rowData = {{"Hello", "World"}};
    private static final Object[] columnNames = {"A", "B"};

    private JTable table;
    private DefaultTableModel model;

    public Grow() {
         Container c = getContentPane();
         c.setLayout(new BorderLayout());

         model = new DefaultTableModel(rowData, columnNames);
         table = new JTable();
         table.setModel(model);
         c.add(new JScrollPane(table), BorderLayout.CENTER);
         JButton add = new JButton("Add");
         c.add(add, BorderLayout.SOUTH);
         add.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
                 model.addRow(rowData[0]);
             }
         });
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         pack(); 
    }

    public static void main(String[] args) {
        Grow g = new Grow();
        g.setLocationRelativeTo(null);
        g.setVisible(true);
    }
}


I assume You have a table with six column. Follow this code ,it will append a new row to already existing table

DefaultTableModel defaultModel = (DefaultTableModel) table.getModel();
        Vector newRow = new Vector();
        newRow.add("Total Amount Spend");
        newRow.add(TotalAmt);
        newRow.add(Apaid);
        newRow.add(Bpaid);
        newRow.add(Cpaid);
        newRow.add(Dpaid);
        defaultModel.addRow(newRow); 

Where JTable table = new JTable(data, columnNames);


The DefaultTableModel has an addRow(...) method that you should be using.

If you need more help then post your SSCCE that demonstrates the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜