从 JList 获取多个对象并将它们添加到数组?

Get multiple Objects from JList and add them to an Array?

我在完成这部分作业时遇到了问题。

This panel also contains a JList object containing the following 10 Canadian universities: Toronto, York, Western, Brock, Guelph, Waterloo, McGill, Concordia, Laval and Macmaster. From that list the user will select 3 universities. A Button labeled "Submit" displayed at the bottom of the panel allows the user to enter the input data coming from textfields and JList object into an array with maximum 100 Student objects.

我已经为 10 所大学创建了一个字符串数组。

  String uniNames[] = {"Toronto", "York", "Western", "Brock", 
     "Guelph", "Waterloo", "McGill", "Concordia", "Laval", "Macmaster"};

该字符串数组已添加到 JList

  JList<String> uniList = new JList<>(uniNames); //(2)
  uniList.setVisibleRowCount(10);
  uniList.setFixedCellHeight(34);
  uniList.setFixedCellWidth(300);
  uniList.setSelectionMode(
     ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  //Add to uniPanelList
  uniPanelList.add(uniList);
  //Add to uniPanel
  uniPanel.add(label3, BorderLayout.NORTH);
  uniPanel.add(uniPanelList, BorderLayout.CENTER);

我创建了提交按钮,它接受输入数据

  submitButton.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent submit){
        String name = "", mark = "";
        int markNum;
        if (submit.getSource()==submitButton){ //If submit is pressed
           name = nameInput.getText(); 
           mark = markInput.getText();
           markNum = Integer.parseInt(mark); //Convert String to int


           //copyList.setListData(colorList.getSelectedValues());
           //String objs = uniList.getSelectedValuesList();


           //Add information to Array, count++ to keep track
           stuArray[count++] = new Student (name, markNum);
           nameInput.setText(""); //Resets input area
           markInput.setText(""); //Resets input area
           //Set label under submit button
           outputLabel.setText("Student " + count + 
              " out of 100 submitted.");
        }
     }
  });

我在处理程序必须 select 3 从我的 JList 中的部分时遇到问题,按提交然后它进入数组。我试过 getSelectedValuesList(),但它 returns 出错了。

列表无法转换为字符串 字符串对象 = uniList.getSelectedValuesList();

我一直在想从这里继续下去。有什么建议吗?

错误消息说明了您所需要的一切:

列表无法转换为字符串

改为:

String objs = uniList.getSelectedValue().toString();

toArray() function of java.util.List 可能就是您要找的。根据 Javadoc:

Returns an array containing all of the elements in this list in proper sequence.

submitButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent submit) {
        String[] selectedUniversities = uniList.getSelectedValuesList().toArray(new String[] {});
    }
});