如何按列索引访问列?

时间:2014-03-10 12:45:53

标签: java jtable

    model = new DefaultTableModel(data, columnNames) 
    {            
        @Override
        public String getColumnName(int col) {
            return (String) columnNames[col];
        }
    };

   table = new JTable(model); 

   for (int tc=0; tc<table.getColumnCount(); tc++)
        table.getColumn(tc).setCellRenderer(new TextAreaRenderer());

我需要按列索引访问列。发生以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Identifier not found
at javax.swing.table.DefaultTableColumnModel.getColumnIndex(Unknown Source)
    at javax.swing.JTable.getColumn(Unknown Source)

2 个答案:

答案 0 :(得分:1)

您需要使用列名来获取列,如下所示:

 for (int tc=0; tc<table.getColumnCount(); tc++)
        table.getColumn(columnNames[tc]).setCellRenderer(new TextAreaRenderer());

答案 1 :(得分:0)

TableColumnModel具有getColumn(int columnIndex)方法:

TableColumnModel columnModel = table.getColumnModel();
for (int tc = 0; tc < table.getColumnCount(); tc++)
    columnModel.getColumn(tc).setCellRenderer(new TextAreaRenderer());