为什么列表值保持不变?

时间:2017-01-09 15:02:32

标签: java list

我想根据JComboBox的索引动态更改列表的值。我有JComboBox我获取索引并将其返回到我班级的某个地方重用。

查看

public class Frame extends JFrame
{
JComboBox firstCombo;
public Frame()
{
    addComponents(getContentPane());
    setVisible(true);
    pack();
}

public void addComponents(Container pane)
{
    firstCombo = new JComboBox();
    firstCombo.addActionListener(listener);
    add(firstCombo);

    DefaultComboBoxModel cbModel = new DefaultComboBoxModel(setGender());
    firstCombo.setModel(cbModel);

    int i = 0;
    Model m = new Model(i);

    List list = m.getName();

    for(Object s : list)
    {
        System.out.println(s);
    }
}

ActionListener listener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource() == firstCombo)
        {
            int i = firstCombo.getSelectedIndex();
            Model model = new Model(i);
            model.setIndex(i);
        }
    }
};
}

模型

public class Model 
{
int a;

public Model(int a)
{
    this.a = a;
}

public static String[] setGender()
{
    return new String[] {"Male", "Female"};
}

public void setIndex(int i)
{
    this.a = i;
}

public int getIndex()
{
    return a;
}

public List getName()
{
    List list = new ArrayList();

    if(getIndex() == 0)
    {
        list.add("Male");
    }
    else if(getIndex() == 1)
    {
        list.add("Female");
    }
    return list;
}

}

public class Jcombo {


public static void main(String[] args) {
    Frame frame = new Frame();
}

}

但是当我在视图中调用此方法return list时,返回列表(getName())保持不变。有什么原因吗?

1 个答案:

答案 0 :(得分:1)

ActionListener listener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource() == firstCombo)
        {
            int i = firstCombo.getSelectedIndex();
            Model model = new Model(i);
            model.setIndex(i);
        }
    }
};

您正在为每个操作重新创建Model的新实例,然后更新索引,因此model将丢失,垃圾收集器将负责处理。保持model实例稍后重用。

注意:getName返回一个List,但在其中,您始终创建一个新实例并添加一个值。不确定为什么