2

我想向已经初始化的 JTable 添加行。除了其他元素之外,我还有以下(相关)代码:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

class sscce extends JFrame {

private static final long serialVersionUID = 1L;    // Serial ID...

// Interface-Elemente erzeugen
Container content = getContentPane();

DefaultTableModel myAbstractTableModel = new DefaultTableModel () {
    private static final long serialVersionUID = 1L;    // whatever
    public String[] columnNames = {"AuftragNr", "Datum & Uhrzeit", "Von", "Nach", "erledigt?"};
    public Object[][] data = {{"156", "31.12.2012 - 10:39:31", "5/5", "205/39", 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];
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    public boolean isCellEditable(int row, int col) {
        if (col != 4) {
            return false;
        } else {
            return true;
        }
    }

    public void setValueAt(Object value, int row, int col) {
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }
};

JTable auftragTable = new JTable(myAbstractTableModel);
JScrollPane tableScrollPane = new JScrollPane(auftragTable);
JButton auftragAenderungSpeichern = new JButton("speichern");

public sscce() {
    setTitle("Auftragsverwaltung");
    setSize(700, 500);
    setLocation(500, 200);
    setLayout(null);
    setResizable(false);
    tableScrollPane.setBounds(50, 50, 500, 200);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

public void actionPerformed(ActionEvent e) {

}

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    JFrame f = new sscce();
    f.show();
}
}

每当我尝试运行程序时,我都会收到NullPointerException以及

at javax.swing.table.DefaultTableModel.setDataVector(Unknown Source)
at javax.swing.table.DefaultTableModel.<init>(Unknown Source)
at javax.swing.table.DefaultTableModel.<init>(Unknown Source)
at javax.swing.table.DefaultTableModel.<init>(Unknown Source)

对于以下代码行:

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

这是为什么?我的代码有什么问题?程序不应该能够“找到”数据吗?


编辑:第二种方法

我尝试使用 ArrayList 作为存储数据的地方......但是下面的评论中标记了“cols-rows-issue”......找不到数组值(因为我现在使用 ArrayList )。我该如何解决?

import java.awt.Container;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

class sscce extends JFrame {

private static final long serialVersionUID = 1L;    // Serial ID...

Container content = getContentPane();

AbstractTableModel myAbstractTableModel = new AbstractTableModel () {
    private static final long serialVersionUID = 1L;    // whatever
    private String[] columnNames = {"AuftragNr", "Datum & Uhrzeit", "Von", "Nach", "erledigt?"};
    private ArrayList<Object> data = new ArrayList<Object>();


    public void addRow(List rowData) {
        data.add(rowData);
        fireTableRowsInserted(data.size() - 1, data.size() - 1);
    }
    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
        // can be solved via .size();
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        return data[row][col];
        // no idea, how to solve that?!
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    public boolean isCellEditable(int row, int col) {
        if (col == 4) {
            return true;
        }
        return false;
    }

    public void setValueAt(Object value, int row, int col) {
        data[row][col] = value;
        // same issue here...
        fireTableCellUpdated(row, col);
    }
};

JTable auftragTable = new JTable(myAbstractTableModel);
JScrollPane tableScrollPane = new JScrollPane(auftragTable);
JButton auftragAenderungSpeichern = new JButton("speichern");

public sscce() {
    setTitle("Auftragsverwaltung");
    setSize(700, 500);
    setLocation(500, 200);
    setLayout(null);
    setResizable(false);
    tableScrollPane.setBounds(50, 50, 500, 200);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    JFrame f = new sscce();
    f.show();
}
}

编辑:第三种方法

sscce 类:

import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

class sscce extends JFrame {

    private static final long serialVersionUID = 1L;    // Serial ID...

    Container content = getContentPane();

    AbstractTableModel myAbstractTableModel = new AbstractTableModel() {
        private static final long serialVersionUID = 1L;    // whatever
        private String[] columnNames = {"AuftragNr", "Datum & Uhrzeit", "Von", "Nach", "erledigt?"};
        private ArrayList<DataStore> data = new ArrayList<DataStore>();


        public void addRow(DataStore rowData) {
            data.add(rowData);
            fireTableRowsInserted(data.size() - 1, data.size() - 1);
        }
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.size(); // length
            // can be solved via .size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
//          change made here
            DataStore rowElement = data.get(row);
            Object value = rowElement.getItemOnPosition(col);
            return value;
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        public boolean isCellEditable(int row, int col) {
            if (col == 4) {
                return true;
            }
            return false;
        }

        public void setValueAt(Object value, int row, int col) {
            // change made here
            DataStore rowElement = data.get(row);
            rowElement.setItemOnPosition(col, value);
            fireTableCellUpdated(row, col);
        }
    };

    JTable auftragTable = new JTable(myAbstractTableModel);
    JScrollPane tableScrollPane = new JScrollPane(auftragTable);
    JButton auftragAenderungSpeichern = new JButton("speichern");

    public sscce() {
        setTitle("Auftragsverwaltung");
        setSize(700, 500);
        setLocation(500, 200);
        setLayout(null);
        setResizable(false);
        tableScrollPane.setBounds(50, 50, 500, 200);

        content.add(tableScrollPane);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        JFrame f = new sscce();
        f.show();
    }
}

数据存储类:

public class DataStore {

    Integer auftragNr;
    String datumUhrzeit;
    String von;
    String nach;
    Boolean status;

    public DataStore(Integer a, String b, String c, String d, Boolean e) {
        auftragNr = a;
        datumUhrzeit = b;
        von = c;
        nach = d;
        status = e;
    }

    public Object getItemOnPosition(int pos) {
        if(pos == 1) {
            return (Integer) auftragNr;
        }
        if(pos == 2) {
            return datumUhrzeit;
        }
        if(pos == 3) {
            return von;
        }
        if(pos == 4) {
            return nach;
        }
        if(pos == 5) {
            return (Boolean) status;
        }
        return null;
    }

    public Object setItemOnPosition(int pos, Object newValue) {
        if(pos == 1) {
            auftragNr = (Integer) newValue;
        }
        if(pos == 2) {
            datumUhrzeit = (String) newValue;
        }
        if(pos == 3) {
            von = (String) newValue;
        }
        if(pos == 4) {
            nach = (String) newValue;
        }
        if(pos == 5) {
            status = (Boolean) newValue;
        }
        return null;
    }
}
4

2 回答 2

3

由于您尝试自己制作myAbstractTableModel,因此您应该扩展AbstractTableModel而不是像DefaultTableModel. 使用 ArrayList 来存储您的数据对象。如何使用表格向您展示了如何执行此操作的基础知识。

顺便说一句,如果没有理由,使您的字段的可见性尽可能低。

public boolean isCellEditable(int row, int col) {
        if (col != 4) {
            return false;
        } else {
            return true;
        }
    }

只做

public boolean isCellEditable(int row, int col) {
        return col == 4;
   }
于 2013-07-14T19:31:50.253 回答
2

我尝试使用 ArrayList 作为存储数据的地方......但是下面的评论中标记了“cols-rows-issue”......找不到数组值(因为我现在使用 ArrayList )。我该如何解决?

是的,因为您没有使用数组,所以无法找到数组值。您将需要从 ArrayList 中提取数据。如果您不熟悉 ArrayList 方法,请查看ArrayList API

关于你的代码,你有编译错误,无论你在哪里发现这些类型的错误,你都必须看看你可能做错了什么。主要是您试图将 ArrayList 视为一个数组,当然它不是,因此使用 array.length 或使用数组索引 (array[i][j]) 的数组类型构造将失败。同样,请查看上面链接的 ArrayList API 或一个不错的 ArrayList 教程,了解如何使用这些家伙。例如,如果编译器告诉您 ArrayList 没有长度属性或方法,那么请在 ArrayList API 中查找获取所需信息的适当方法。这就是 API 的用途。

此外,您的 ArrayList 不应该包含 Object,换句话说,它不应该包含ArrayList<Object>但应该更具体。通常,表模型的行将包含一个对象,其属性代表行的每个项目。因此,如果我们调用保存每行数据 RowData 的类,您的 ArrayList 将被声明为ArrayList<RowData>. 因此,要在行 col 中获取值,您需要从模型的 ArrayList 中提取行索引的 RowData(假设这是行数据类的名称),然后调用对象的 getter 方法来提取 col 索引-相关项目。

于 2013-07-14T19:19:24.547 回答