在JTable中设置列的数据类型

时间:2011-09-15 10:05:08

标签: java swing jtable

我用表模型创建了一个JTable。现在基于我的输入,我想将一列写入特定的数据类型。我该怎么做?

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

public class MyTableModelTwo extends AbstractTableModel {

    private static final long serialVersionUID = 1L;
    private Object[][] data;
    private String[] columnNames;

    public MyTableModelTwo(Object[][] data) {
        this.data = data;
    }

    @Override
    public int getRowCount() {
        return data.length;
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }

    @Override
    public Class<?> getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    @Override
    public boolean isCellEditable(int rowIndes, int columnIndex) {
        return true;
    }

    @Override
    public String getColumnName(int index) {
        return columnNames[index];
    }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {
        data[rowIndex][columnIndex] = value;
        fireTableCellUpdated(rowIndex, columnIndex);
    }

    public MyTableModelTwo(String[] columnNames, Object[][] data) {
        this.columnNames = columnNames;
        this.data = data;
    }
}

class MyTableTwo extends JPanel implements TableModelListener {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private Object[][] data;
    private JTextField t;

    public MyTableTwo(int noElements, String[] columnNames) {
        data = new Object[noElements][columnNames.length];
        t = new JTextField();
        MyTableModelTwo m = new MyTableModelTwo(columnNames, data);
        table = new JTable(m);
        table.getModel().addTableModelListener(this);
        setLayout(new GridLayout(1, 0));
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    @Override
    public void tableChanged(TableModelEvent e) {
    }

    public JTextField returnT6() {
        return t;
    }
}

2 个答案:

答案 0 :(得分:3)

覆盖public Class getColumnClass(int column) {...

请问我的问题,为什么你需要AbstractModel,为什么原因,你真的想要restict / mofify / change / override,(you can prety ignore this == be sure that not really not good way to start to playing with anything for JTable based on AbstractTableModel),但是...考虑使用DefalutTableModel而不是AbstractTableModel

答案 1 :(得分:-2)

我的立场得到了纠正,但我不认为JTable中的列(或单元格)有任何数据类型的概念。您最好检查预期的整数,否则抛出异常。例如:

try{
  Integer.parseInt(myTableCellValue);
}catch(ParseException e){
  //Not a valid integer
}