我正在尝试填充JTable对象,但是当指令
private final DefaultTableModel tarifModel = (DefaultTableModel) tbTarife.getModel();
被调用,我收到了NullPointerException。
我正在使用Netbeans 8.2和GUI Builder插件来创建JTable。
我已经实现了here中描述的部分,而涉及此问题的其他任何问题似乎都不适用。
我的代码:
public class TarifDialog extends javax.swing.JPanel {
private final TarifParser tP;
public TarifDialog() {
initComponents();
tP = new TarifParser(this);
}
//Generated code
private void initComponents() {
tbTarife = new javax.swing.JTable();
scrollpTarife = new javax.swing.JScrollPane();
tbTarife.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Schlüssel", "Name", "Beschreibung", "Preis", "Typ"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
scrollpTarife.setViewportView(tbTarife);
}
private javax.swing.JScrollPane scrollpTarife;
private javax.swing.JTable tbTarife;
//End generated code
private final DefaultTableModel tarifModel = (DefaultTableModel) tbTarife.getModel();
public void addTarifToTable(String Key, String name, String description, double price, String type) {
tarifModel.addRow(new Object[]{Key, name, description, price, type});
}
}
以及访问它的类:
public final class TarifParser {
private final TarifVerwaltung tV;
private final TarifDialog tD;
public TarifParser(TarifDialog tD) {
this.tV = Init.getTarifVerwaltung();
this.tD = tD;
populateTarifTable();
}
public void populateTarifTable() {
for (HashMap.Entry<String, Tarif> tariff : tV.getAllTariffs().entrySet()) {
String type = "Undefined";
if (tariff.getValue().getType() == 0) {
type = "Standard Tarif";
} else if (tariff.getValue().getType() == 1) {
type = "Wiederkehrender Tarif";
} else if (tariff.getValue().getType() == 2) {
type = "Einmaliger Tarif";
}
tD.addTarifToTable(tariff.getKey(), tariff.getValue().getName(), tariff.getValue().getDescription(), tariff.getValue().getPrice(), type);
}
}
}