AbstractTableModel中的对象初始化

时间:2016-07-14 19:15:50

标签: java swing jtable abstracttablemodel object-initialization

我正在开发一个小程序,它应该在JTable中显示收件人。 一切似乎都运行良好,我唯一的问题是我无法初始化应该正确保存数据的对象。这是让我头疼的课程:

class RecipeTableModel extends AbstractTableModel {

    private String[] columnNames = {"Number", "Name", "Difficulty",
        "Preparation", "PreparationTime", "Quantity", "Incredients"};
    Recipe recipe1 = new Recipe("1", "SecretRecipe", "easy", "microwave", "20min", "100gr", "flour");
    Recipe recipe2 = new Recipe("2", "SuperRecipe", "medium", "microwave", "30min", "100gr", "Salt");
    **RecipeDB recipeDB = new RecipeDB();
    recipeDB.addRecipe (Recipe recipe1);**


    @Override
    public int getColumnCount() {
        return 7;
    }

    public int getRowCount() {
        //return recipeDB.getRecipeDBSize();
        return 15;
    }

    @Override
    public Object getValueAt(int row, int col) {

    /*  Recipe recipe = recipeDB.getRecipe(row);
        switch (col){
        case 0:
            return recipe.getNumber();
        case 1:
            return recipe.getName();
        case 2:
            return recipe.getPrep();
        case 3:
            return recipe.getPrepTime();
        case 4:
            return recipe.getDifficulty();
        case 5:
            return recipe.getIngredients(); 
        }
        */
        return null;
    }

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

当我尝试将收件人添加到recipeDB时出现语法错误;当我调试时,我看到recipeDB被初始化为null值。这怎么可能?

这是我的另一堂课:

import java.util.ArrayList;

public class RecipeDB {

    public ArrayList<Recipe> recipeArraylist;

    public RecipeDB() {
        recipeArraylist = new ArrayList<Recipe>();
    }

    public void addRecipe(Recipe recipe) {
        recipeArraylist.add(recipe);
    }

    public int getRecipeDBSize() {
        return recipeArraylist.size();
    }

    public Recipe getRecipe(int i) {
        return recipeArraylist.get(i);
    }

    public ArrayList getDBArrayList() {
        return recipeArraylist;
    }
}

1 个答案:

答案 0 :(得分:1)

语法错误来自尝试在RG_free()的{​​{3}}部分recipeDB上调用实例方法。

RecipeTableModel

方法调用在class body declaration或构造函数中是合法的。在下面的例子中,都不需要;使用RecipeDB recipeDB = new RecipeDB(); // legal declaration and initialization recipeDB.addRecipe (Recipe recipe1); // illegal method invocation 方法在循环中添加Recipe存根的实例。

instance initializer

addRecipe()