[英]Java: JTable change listener, “Object cannot be converted to string” error
I have a JTable
, and a class which is supposed to control to the program's response to various actions, the first of which I am writing is for a cell change event. 我有一个
JTable
,一个应该控制程序对各种动作的响应的类,我写的第一个是用于单元格更改事件。
Each row is generated from a Part
object, and the column class of each column is set correspondingly. 每行都是从
Part
对象生成的,每列的列类都相应地设置。
Part(String partName, String make, String partNumber,
String altPartNumber, Double price, Integer quantity,
String description, Boolean isAutomotive, Boolean isMarine,
Boolean isIndustrial)
{
//...code not shown...
}
Part objects are stored in a serializable ArrayList<Part>
. 零件对象存储在可序列化的
ArrayList<Part>
。
Essentially, what the event handling code needs to do is update the value of a parameter of a particular part object within this ArrayList
using the updated data obtained from the JTable
. 本质上,事件处理代码需要做的是使用从
JTable
获得的更新数据更新此ArrayList
特定部件对象的参数值。
Below is the code that demonstrates how I want to do this; 下面的代码演示了我想如何做到这一点; herein the error mentioned in the title occurs.
这里出现标题中提到的错误。 Can anyone explain how to deal with this problem?
任何人都可以解释如何处理这个问题?
public class EventController extends UI implements TableModelListener
{
// Declarations:
private int row;
private int column;
private Part partToChange;
// ...Omitted for brevity...
private String updatedName;
private String updatedMake;
private Integer updatedQuantity;
// Don't need declarations for the booleans, can just toggle them.
@Override
public void tableChanged(TableModelEvent e)
{
// Find out where the change took place...
this.column = e.getColumn();
this.row = e.getFirstRow();
// Get the new value...
// Send the new value to parts...
partToChange = data.getPart(row);
switch(column)
{
case 0:
updatedName = getTableModel().getValueAt(row, column);
// ERROR OCCURS HERE ^
partToChange.setName(updatedName);
}
}
}
Your getTableModel().getValueAt(row, column);
你的
getTableModel().getValueAt(row, column);
returns an Object reference and not a String, but you're assigning it to a String variable. 返回一个Object引用而不是String,但是您将它分配给String变量。 Your choices include:
您的选择包括:
toString()
on it. toString()
。 Here if it's not a String, you won't get an exception, but the String returned might not be what you want to use. String.valueOf()
you would avoid the null exception issue of toString()
. String.valueOf()
您可以避免toString()
的null异常问题。 Thank you Richard!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.