0

我有一个小问题,我不知道如何按从数据库中检索到的状态对我的 jlist 进行排序。我想按“在线”和“离线”排序,我的意思是先在线计算机然后离线计算机,我现在有这个代码,它只是为 jlist 制作图标+文本

你能告诉我如何过滤/排序状态吗?

public void acx_pc(String query) {
    try {
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query);
        String comb;
        Map<Object, Icon> icons = new HashMap<>();
        ArrayList<String> pc_list = new ArrayList<>();
        int i = 0;


        while (rs.next()) {
            //Getting info from DB

            String pc_name = rs.getString("nombre_pc");
            String pc_ip = rs.getString("IP");
            String status = rs.getString("estado");
            //Setting text for the jList
            comb = pc_name + " - " + pc_ip;
            //Comparing Status
            switch (status) {
                case "online":
                    //This is just for rendering an image+text to Jlist
                    icons.put(comb, new ImageIcon(getClass().getResource("/Imagenes/com_on_30x30.png")));

                    break;
                case "offline":
                     //This is just for rendering an image to Jlist
                    icons.put(comb, new ImageIcon(getClass().getResource("/Imagenes/com_off_30x30.png")));
                    break;
            }
            //Adding info to ArrayList
            pc_list.add(i, comb);
            i++;

        }

        con.close();
        // Setting the list/text on Jlist
        Home.computer_jlist.setListData(pc_list.toArray());
        // create a cell renderer to add the appropriate icon
        Home.computer_jlist.setCellRenderer(new pc_cell_render(icons));

    } catch (Exception e) {
        System.out.println("Error aqui: " + e);

    }
}

我想做类似(应该自动订购) http://imageshack.us/a/img27/9018/2mx1.png

而不是:http: //imageshack.us/a/img407/346/e9r.png

4

1 回答 1

2

您可以pc_list使用Collections.sort自定义的实用程序方法对您的Comparator.

但是,这可能是矫枉过正。只使用两个列表会更容易:

ArrayList<String> pc_list = new ArrayList<>();
ArrayList<String> pc_offline_list = new ArrayList<>();

// . . .

switch (status) {
    case "online":
        //This is just for rendering an image+text to Jlist
        icons.put(comb, new ImageIcon(getClass().getResource("/Imagenes/com_on_30x30.png")));
        pc_list.add(comb);
        break;
    case "offline":
         //This is just for rendering an image to Jlist
        icons.put(comb, new ImageIcon(getClass().getResource("/Imagenes/com_off_30x30.png")));
        pc_offline_list.add(comb);
        break;
}

// . . .

pc_list.addAll(pc_offline_list);
Home.computer_jlist.setListData(pc_list.toArray());

因此,您首先将离线的那些分开,然后将它们全部粘贴到您找到它们的最后一个。通过将它们分开,避免进行任何排序!

此外,该add方法默认添加到末尾(追加),因此您会注意到我只是写了pc_list.add(comb)而不是pc_list.add(i, comb).

于 2013-06-29T04:18:05.083 回答