首页 > 解决方案 > 从默认表模型JAVA获取对象

问题描述

我想知道如何将对象(产品)放入表中,然后稍后将其作为对象检索。

例子 :

public class Controller {

    public Controller() {
        View view = new View(this);
        DefaultTableModel viewDtm = view.getDefaultTableModel();

        //The product i want to put in to the table, and retrieve later on.
        Product product1 = new Product(1,"Cola",2.54);

        viewDtm.addRow(new Object[]{
                product1.getId().toString(),
                product1.getName(),
                product1.getId().toString()
        });
    }
}

我将如何在另一个类中检索 product1 ?

标签: javaswing

解决方案


How would i retrieve the product1 in another class ?

As written you can't do this, and this has nothing to do with JTable, TableModel, or Swing and all to do with your variables all being declared local to the constructor. Just like non-Swing, non-GUI programs, if you want other classes to be able to check the state of an object, the object's key fields should be instance (non-static) fields of the class, and you should give them getter (accessor) methods.

Your code is akin to this:

public class Foo {
    public Foo() {
        Bar bar = new Bar();
    }
}

In this set up, bar is completely inaccessable to outside classes. Instead you want something more like:

public class Foo {
    private Bar bar = new Bar();

    public Foo() {
        // Bar bar = new Bar();
    }

    public Bar getBar() {
        return bar;
    }
}

Side note: I would make my own TableModel class that extended DefaultTableModel or AbstractTableModel, and would also give it methods that allow easy addition of a row, passing in an object of a specific type, as well as getting a row of data, returning a custom object of specific type.


推荐阅读