【问题标题】:How to place ArrayList into an AbstractTableModel?如何将 ArrayList 放入 AbstractTableModel?
【发布时间】:2020-02-26 19:58:46
【问题描述】:

我有一个ArrayList<String[]> data,我将值放入程序中的不同点,我已将其设为 MyTable 的变量,该变量扩展了 AbstractTableModel。但我不知道如何将其放入表中。

我之前已将String[][] 放入表中,但我不确定这将如何与 ArrayList 类一起使用。

对于getRowCount(),我可以使用newStringArr.length,对于getColumnCount,我可以使用newStringArr[0].length,对于getValueAt(int row, int column),我可以返回newStringArr[row][column],以获得String[][]类型。 ArrayList 的这些功能是什么?

【问题讨论】:

  • 这适用于 Swing、JavaFX、SWT、Vaadin 吗?为您正在使用的任何 UI 工具包添加标签。

标签: java swing arraylist


【解决方案1】:

Here 是使用AbstractTableModel 的一个很好的例子。 在您的情况下,MyTable 可以定义为:

class MyTable extends AbstractTableModel {
    private final int numRows;
    private final int numColumns;

    private List<String[]> data = new ArrayList<String[]>();

    public MyTable(int numColumns, int numRows) {
        this.numColumns = numColumns;
        this.numRows = numRows;

        init();
    }

    public int getColumnCount() {
        return data.get(0).length;
    }

    public int getRowCount() {
        return data.size();
    }

    public Optional<String> getValueAt(int row, int col) {
        if(isNotValidEntry(row, col)) {
            throw new RuntimeException("Out of bound row or col");
        }

        return Optional.ofNullable(data.get(row - 1)[col -1]);
    }

    public void setValueAt(String value, int row, int col) {
        if(isNotValidEntry(row, col)) {
            throw new RuntimeException("Out of bound row or col");
        }

        data.get(row - 1)[col - 1] = value;
        fireTableCellUpdated(row, col);
    }

    private void init() {
        IntStream.range(0, numRows)
                .forEach(r -> data.add(new String[numColumns]));
    }

    private boolean isNotValidEntry(int row, int col) {
        return numRows <= row - 1 || numColumns <= col - 1;
    }

}

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 2011-10-10
    • 2014-11-25
    • 2013-01-12
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多