如何按字母顺序对JList中的项目进行排序?

时间:2015-07-03 09:40:03

标签: java arraylist collections jlist

基本上我要做的是创建一个显示大量名称的程序。我正试图在列表中按字母顺序对名称进行排序。我正在使用ArrayList。我知道我可以使用集合按字母顺序对它们进行排序,但如果在这种情况下我使用的是对象(NPC),我该怎么做呢

这就是它的样子。

enter image description here

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NPC {

public ArrayList<NPC> npcs = new ArrayList<NPC>();

private int id; 
private String name;
static String file_name = "./npclist.txt";

public NPC(int id, String name) {
    this.id = id;
    this.name = name;
}

public static void loadNPCs(java.io.File file) {
    new ReadFile(file_name);
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void sortByName() {
    for(int i=0; i < npcs.size(); i++){
        String name = npcs.get(i).getName();
        names.add(name);
    }
    Collections.sort(names);

    for(String counter: names) {
        System.out.println(counter);
    }
}

public void setName(String name) {
    this.name = name;
}
}

我的单选按钮

        this.radioBtn = new JRadioButton("Sort by: " + (toggleBtn ? "ID" : "Names"));
    radioBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == radioBtn) {
                if (toggleBtn) {
                    sortByID(e);
                    toggleBtn = false;
                    radioBtn.setText("Sort by: " + (toggleBtn ? " ID" : "Names"));
                    radioBtn.setPreferredSize(new Dimension(108, 12));
                } else if (!toggleBtn) {
                    sortByName(e);
                    toggleBtn = true;
                    radioBtn.setText("Sort by: " + (toggleBtn ? "ID" : "Names"));
                    radioBtn.setPreferredSize(new Dimension(108, 12));
                }
            }
        }       
    });
    gbc.insets = new Insets(5, 5, 5, 16);
    gbc.anchor = GridBagConstraints.LINE_END;
    gbc.gridx = 0;
    gbc.gridy = 1;

    panel.add(radioBtn, gbc);

和我的默认列表模型

    private DefaultListModel<String> itemListModel() {
    listModel = new DefaultListModel<String>();
    for (NPC npc : ReadFile.getNPCs()) {
        if (npc != null) {
            listModel.addElement(npc.getName());
        }
    }
    return listModel;
}

1 个答案:

答案 0 :(得分:0)

NPC应该实现Comparable接口。 为compareTo方法提供实现