java - 从默认表模型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 ?
解决方案
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.
推荐阅读
- java - 为什么即使 MethodHandle 正常,我也会在 invokeExact 上得到 WrongMethodTypeException
- sql - 在 SQL 中生成所有可能的组合?
- c++ - _CrtSetDbgFlag 未按预期工作:返回 NULL
- c++ - 在函数中使用传递的参数列表
- java - 如何在 JAVA servlet 方法中注入字符串?
- php - 获取未分配给 WooCommerce 变体的购物车项目产品属性
- apache-camel - 使用 camel-smb SMB 拾取(大)文件,同时仍被写入
- php - PHP / Laravel 不接受 .upd 文件作为文件
- python - Flakehell 忽略 darglit 的附加 setup.cfg 参数
- matlab - 如何找到平稳概率分布并确定状态概率将在哪一步保持不变