java为什么我的ArrayList的add方法冲突,如何编辑我的自定义add方法
我已经找到了为什么我的arraylist总是返回0的大小,但我无法解决这个问题。我有一个带有“addHuman(Human h)方法的自定义模型,该方法旨在添加到数组中。唯一的问题是它没有。现在,如果我使用常规方法,比如model.add(index,object o)它实际上会工作并增加我的arraylist的大小,但不会显示在我的jtable上。我的问题是,我如何才能使我的自定义addHuman方法工作?非常感谢任何帮助
下面是使用该方法的主类。当我点击addIndividual按钮时,它应该将human添加到我的HumanListModel中:
addIndividual.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Human temp;
try {
temp = new Human();
modelx.addHuman(indexPoint, temp);
///the addHuman method does display on jtable but doesn't increment arraylist, meaning that the size is always 0 which creates many problems/////
//modelx.add(indexPoint, temp); does indeed increment the arraysize but then it doesn't display the values on the jtable////
indexPoint++;
System.out.println(modelx.size());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
newbiex.revalidate(); ////is the jtable////
}
});
以下是我的自定义HumanListModel:
public class HumanListModel extends DefaultListModel implements TableModel
{
private ArrayList<Human> data;
public HumanListModel()
{
super();
data = new ArrayList<Human>();
}
public void addHuman(int k, Human h)
{
data.add(k, h);
fireIntervalAdded(this, data.size(), data.size());
}
public Human getHuman(int o)
{
return data.get(o);
}
public void removeHuman(Human h)
{
data.remove(h);
}
public int getColumnCount()
{
// the number of columns you want to display
return 1;
}
public int getRowCount()
{
return data.size();
}
public Object getValueAt(int row, int col)
{
return (row < data.size()) ? data.get(row) : null;
}
public String getColumnName(int col)
{
return "Human";
}
public Class getColumnClass(int col)
{
return Human.class;
}
public void addTableModelListener(TableModelListener arg0) {
}
@Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
public void removeTableModelListener(TableModelListener arg0) {
}
public void setValueAt(Object arg0, int arg1, int arg2) {
}
}
# 1 楼答案
当您更改基础模型的数据时,必须触发模型更改
每当您更改基础数据时,需要调用具有类似事件的类似方法来告诉列表它必须更新屏幕图像
例如,
removeHuman()
将需要一个类似的调用。请参阅位于http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractListModel.html的javadoc,以了解执行此操作的方法。(在本例中,fireIntervalRemoved()
,事件需要包含删除行的索引。)您还需要一个
getElementAt()
方法来返回该行的数据元素。在您的情况下,返回该行的Human
,但它需要一个toString()
方法。或者,您可以从Human
中格式化字符串 然后把它还给我注意-这个答案的前一个版本是基于我的困惑,认为这是一个表格模型而不是列表模型。已经修好了