import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;public class Test extends JFrame {
  private int rows = 3, cols = 5;
  private Object[] rowData = new Object[cols];  private DefaultTableModel model = new DefaultTableModel();
  private JTable table = new JTable(model);  public Test() {
    for (int c = 0; c < cols; ++c)
      model.addColumn("Column " + Integer.toString(c));    for (int r = 0; r < rows; ++r) {
      for (int c = 0; c < cols; ++c) {
rowData[c] = "(" + r + "," + c + ")";
      }
      model.addRow(rowData);
    }
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    getContentPane().add(new ControlPanel(), BorderLayout.NORTH);
  }  public static void main(String args[]) {
    Test test = new Test();
    test.setBounds(100, 100, 300, 300);
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.show();
  }  class ControlPanel extends JPanel {
    private JButton rowButton = new JButton("Add Row"),
colButton = new JButton("Add Column");    public ControlPanel() {
      add(rowButton);
      add(colButton);      rowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
  int rowCount = model.getRowCount();
  int colCount = model.getColumnCount();   if (colCount > rowData.length)
    rowData = new Object[colCount];   for (int c = 0; c < colCount; ++c) {
    rowData[c] = "(" + rowCount + "," +
c + ")";
  }
  model.addRow(rowData);
}
      });
      colButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
  int colCount = model.getColumnCount();
  model.addColumn("Column " + colCount); }
      });
    }
  }
}

解决方案 »

  1.   

    To yuanmeng163(今天我有空):
    谢谢您的程序,我希望理解的是扩展DefaultTableModel的方法,还要请您继续不吝赐教。我调试了程序,发现了出错的地方
    是 public int getRowCount() 
        {
            //System.out.println("aaaaaaaaaaaaaaaa"+data.size()+"aaaaaaaaaaaaaa");
            return data.size());
        }
    这个函数如果去掉,使用DefaultTableModel就可以正常进行,但只显示表头,
    这个函数加上,则发生错误,
    我查阅了资料,getColumnCount, getRowCount, getValueAt这3个Methods是AbstractTableModel从TableModel那里继承过来的,
    但是DefaultTableModel是直接从Object派生出来的,没有这3个方法,那么该怎么解决这个问题呢?您有扩展DefaultTableModel的例子吗?
      

  2.   

    你错了,DefaultTableModel不是直接从Object派生出来的,而是继承了AbstractTableModel类。
    getRowCount()方法出错,可能是因为data为null.你直接用DefaultTableModel类试试,不用扩展了。
      

  3.   

    我PRINT了data ,值是正确的0,而且我把这里改成return 0、return 1也还是那样的错,真是快疯掉了,明天就要交作业了,5555~~~
      

  4.   

    不仅仅是我的程序,下面这个程序了JAVA的文挡中讲解TABLEMODE的时候的一个例子程序,我把其中的AbstractTableModel 改成DefaultTableModel,还是出现了一加getRowCount()就错的现象,请您帮忙看看。
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;public class TableDemo extends JFrame {
        private boolean DEBUG = true;    public TableDemo() {
            super("TableDemo");        MyTableModel myModel = new MyTableModel();
            JTable table = new JTable(myModel);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));        //Create the scroll pane and add the table to it. 
            JScrollPane scrollPane = new JScrollPane(table);        //Add the scroll pane to this window.
            getContentPane().add(scrollPane, BorderLayout.CENTER);        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }    class MyTableModel extends DefaultTableModel {
            final String[] columnNames = {"First Name", 
                                          "Last Name",
                                          "Sport",
                                          "# of Years",
                                          "Vegetarian"};
            final Object[][] data = {
                {"Mary", "Campione", 
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml", 
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Chasing toddlers", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Angela", "Lih",
                 "Teaching high school", new Integer(4), new Boolean(false)}
            };        public int getColumnCount() {
                return columnNames.length;
            }
            
    //        public int getRowCount() {
    //            return data.length;
    //        }        public String getColumnName(int col) {
                return columnNames[col];
            }        public Object getValueAt(int row, int col) {
                return data[row][col];
            }        /*
             * JTable uses this method to determine the default renderer/
             * editor for each cell.  If we didn't implement this method,
             * then the last column would contain text ("true"/"false"),
             * rather than a check box.
             */
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            }        /*
             * Don't need to implement this method unless your table's
             * editable.
             */
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) { 
                    return false;
                } else {
                    return true;
                }
            }        /*
             * Don't need to implement this method unless your table's
             * data can change.
             */
            public void setValueAt(Object value, int row, int col) {
                if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                                       + " to " + value
                                       + " (an instance of " 
                                       + value.getClass() + ")");
                }            if (data[0][col] instanceof Integer                        
                        && !(value instanceof Integer)) {                  
                    //With JFC/Swing 1.1 and JDK 1.2, we need to create    
                    //an Integer from the value; otherwise, the column     
                    //switches to contain Strings.  Starting with v 1.3,   
                    //the table automatically converts value to an Integer,
                    //so you only need the code in the 'else' part of this 
                    //'if' block.                                          
                    //XXX: See TableEditDemo.java for a better solution!!!
                    try {
                        data[row][col] = new Integer(value.toString());
                        fireTableCellUpdated(row, col);
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(TableDemo.this,
                            "The \"" + getColumnName(col)
                            + "\" column accepts only integer values.");
                    }
                } else {
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
                }            if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
                }
            }        private void printDebugData() {
                int numRows = getRowCount();
                int numCols = getColumnCount();            for (int i=0; i < numRows; i++) {
                    System.out.print("    row " + i + ":");
                    for (int j=0; j < numCols; j++) {
                        System.out.print("  " + data[i][j]);
                    }
                    System.out.println();
                }
                System.out.println("--------------------------");
            }
        }    public static void main(String[] args) {
            TableDemo frame = new TableDemo();
            frame.pack();
            frame.setVisible(true);
        }
    }
      

  5.   

    DefaultTableModel直接带getRowCount()这个函数,您不要再重载了.
      

  6.   

    呵~~刚上网。
    你走的时候说了啊,直接用DefaultTableModel类,不用扩展了啊。你把那个内部类MyTableModel去掉,把里面的
                  String[] columnNames = {"First Name", 
                                          "Last Name",
                                          "Sport",
                                          "# of Years",
                                          "Vegetarian"};
                 
                  Object[][] data = {
                                    {"Mary", "Campione", 
                     "Snowboarding", new Integer(5), new Boolean(false)},
                    {"Alison", "Huml", 
                     "Rowing", new Integer(3), new Boolean(true)},
                    {"Kathy", "Walrath",
                     "Chasing toddlers", new Integer(2), new Boolean(false)},
                    {"Sharon", "Zakhour",
                     "Speed reading", new Integer(20), new Boolean(true)},
                    {"Angela", "Lih",
                     "Teaching high school", new Integer(4), new Boolean(false)}
                    };移到主类中,去掉final关键字,声明DefaultTableModel时这样:
    DefaultTableModel model = new DefaultTableModel(data, clomnNames);
    JTable table = new JTable(model);
      

  7.   

    我的目标主要是让所有的单元格都不可编辑,那样的要求好象只有通过扩展,重新写isCellEditable(int row, int col)才能做到吧?