无法将字符串从JList添加到ArrayList

时间:2018-02-23 19:39:03

标签: java arraylist jlist

我试图将选定的项目从JList(uniOptions)添加到ArrayList(studentChoices),然后传递给一个对象。问题是它只需要第一次选择两次,它应该进行3次选择然后再单独添加到ArrayList。

这是actionListener:

uniOptions.addListSelectionListener(new ListSelectionListener() {

        int selectionsMade=0;
        int[] selectionIndex;
        public void valueChanged(ListSelectionEvent event) {

            selectionIndex = uniOptions.getSelectedIndices();
            if(event.getValueIsAdjusting()) {
                selectionsMade++;
                uniSelection = uniOptions.getSelectedValue();
                System.out.println("Number of Selections made: " + selectionsMade);
                System.out.println(selectionIndex.length); //shows item is selected
        }
    }
});

这是JButton的actionlistener。仅当输入有效时,按钮动作侦听器才会添加JList中的选定值并将其添加到ArrayList。

submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent getProfile){
            boolean validInput = true;

//checks if average is an integer           
            try {
                studentsAverage = Integer.parseInt(averagePromptTF.getText());  
            }catch (NumberFormatException e){
                validInput = false;
                System.out.println("please enter valid input");
            }
//add student information and choices to student object
            if (studentsAverage >75 && validInput && uniSelection != null && studentsAverage < 100) {
                Student person = new Student (namePromptTF.getText(), averagePromptTF.getText(), uniSelection, studentChoices);
                Applicants.add(person);
                arrayCount++;
                numberOfApplicants.setText(arrayCount +"/" +100+"students");
                System.out.println(person.toString());

                studentChoices.add(uniOptions.getSelectedValue());
                for ( int i = 0; i< arrayCount; i++) {
                    studentChoices.add(uniOptions.getSelectedValue());
                }
            }else if (uniSelection == null | studentsAverage <75 | studentsAverage>100 | averagePromptTF == null) {
                System.out.println("choose atleast 3 universities to apply");
                System.out.println("Student average must be between 75 and 100");
            }
            System.out.println(studentChoices);

//clears input after submission
                namePromptTF.setText(null);
                averagePromptTF.setText(null);
                uniOptions.clearSelection();
        }
    });

我得到的输出是

      LastName, average= 95, Waterloo: 

      [Waterloo, Waterloo]

到目前为止,我写的代码只添加了2个选项,并重复添加所选的第一个。预期的输出应该是

  Smith, average=87, York-admitted, McGill-rejected, UofT- rejected

这是上下文代码的其余部分,因为我不确定为什么它不能正常工作

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.EventObject;
import java.awt.event.*;

public class ApplicationCentre extends JFrame implements ActionListener {
private CardLayout CARD_MANAGER;
private JPanel MAIN_PAGE;
private JButton CONTROL[];
private String buttonNames[] = {"INPUT", "DISPLAY ALL", "SEARCH"};
private int arrayCount = 0;//KEEPS TRACK FO THE SIZE OF THE ARRAYLIST
private int studentsAverage; // HOLD STUDENT AVERAGE
private ArrayList<Student> Applicants = new ArrayList<Student>(); //CREATES ARRAY OF STUDENT OBJECTS
private String[] selectionList = {"York","Toronto", "Brock", "Guelph", "Waterloo", "McGill", "Concordia", "Laval", "Macmaster", "Western"};
private JList<String> uniOptions; // JLIST OF UNIVERSITY OPTIONS
ArrayList<String> studentChoices = new ArrayList<String>(); //ARRAYLIST OF OF STUDENT CHOICES
private String uniSelection;


ApplicationCentre (){
    super("Application Centre");
    this.getContentPane();

         //>>CONFIGURE MAIN PAGE        
    MAIN_PAGE = new JPanel();
    CARD_MANAGER = new CardLayout();
    MAIN_PAGE.setLayout(CARD_MANAGER);
    MAIN_PAGE.setPreferredSize(new Dimension(325, 500));

    MAIN_PAGE.add(inputPanel());
    MAIN_PAGE.add(displayAllPanel(), "Display All");
    MAIN_PAGE.add(searchPanel());

    //>>CREATE AND ADD BUTTONS TO CONTROL BOARD 
    JPanel CONTROL_BOARD = new JPanel();
    CONTROL_BOARD.setLayout(new GridLayout (3, 0));
    CONTROL = new JButton[buttonNames.length];

    for(int i = 0; i<buttonNames.length;i++) {
        CONTROL[i]=new JButton(buttonNames[i]);
        CONTROL[i].addActionListener(this);
        CONTROL_BOARD.add(CONTROL[i]);
    }

    //ADD MAIN_PAGE PANEL AND CONTROL_BOARD PANEL TO FRAME
    this.add(MAIN_PAGE, BorderLayout.EAST);
    this.add(CONTROL_BOARD, BorderLayout.WEST);
}
    /***************************************************************///PANEL LAYOUT


JPanel inputPanel() {
    JPanel input = new JPanel();
    input.setLayout(new BoxLayout(input, BoxLayout.Y_AXIS));

   /***********************************INPUT SUB-PANEL***/  
    JPanel namePanel = new JPanel();

    JLabel namePrompt = new JLabel("Enter students name: ");
    JTextField namePromptTF = new JTextField();
    namePromptTF.setColumns(18); 
    namePromptTF.setEditable(true);

    namePanel.add(namePrompt);
    namePanel.add(namePromptTF);
  /***********************************AVERAGE SUB-PANEL***/     
    JPanel averagePanel = new JPanel();

    JLabel averagePrompt = new JLabel("Enter students average: ");
    JTextField averagePromptTF = new JTextField();
    averagePromptTF.setColumns(18); 
    averagePromptTF.setEditable(true);

    averagePanel.add(averagePrompt);
    averagePanel.add(averagePromptTF);

  /***********************************UNIVERSITY SELECTOR SUB-PANEL***/     
    JPanel UniversitySelectorPanel = new JPanel();
    JLabel uniSelector = new JLabel("Please select 3 Universitys to apply to: ");
    uniOptions.setFixedCellWidth(250);
    uniOptions.setFixedCellHeight(20);
    uniOptions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    uniOptions.addListSelectionListener(new ListSelectionListener() {
        int selectionsMade=0;
        int[] selectionIndex;
        public void valueChanged(ListSelectionEvent event) {

            selectionIndex = uniOptions.getSelectedIndices();

            if(event.getValueIsAdjusting()) {
                selectionsMade++;
                uniSelection = uniOptions.getSelectedValue();   

                System.out.println("Number of Selections made: " + selectionsMade);
                System.out.println(selectionIndex.length);

        }
    }
});

    UniversitySelectorPanel.add(uniSelector);
    UniversitySelectorPanel.add(uniOptions);
   /*****************************************/  //SUBMIT BUTTON 
    JPanel bottomPanel = new JPanel(new BorderLayout());
    JLabel numberOfApplicants = new JLabel("No Students have applied");
    JButton submit = new JButton("Submit");



    /*********JBUTTON FUNCTIONALITY*****************/

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent getProfile){
            boolean validInput = true;

  //checks if average is an integer         
            try {
                studentsAverage = Integer.parseInt(averagePromptTF.getText());  
            }catch (NumberFormatException e){
                validInput = false;
                System.out.println("please enter valid input");
            }
  //add student information and choices to student object
            if (studentsAverage >75 && validInput && uniSelection != null && studentsAverage < 100) {
                Student person = new Student (namePromptTF.getText(), averagePromptTF.getText(), uniSelection, studentChoices);
                Applicants.add(person);
                arrayCount++;
                numberOfApplicants.setText(arrayCount +"/" +100+"students");
                System.out.println(person.toString());

                studentChoices.add(uniOptions.getSelectedValue());


                for ( int i = 0; i< arrayCount; i++) {
                    studentChoices.add(uniOptions.getSelectedValue());
                }


            }else if (uniSelection == null | studentsAverage <75 | studentsAverage>100 | averagePromptTF == null) {
                System.out.println("choose atleast 3 universities to apply");
                System.out.println("Student average must be between 75 and 100");
            }
            System.out.println(studentChoices);

   //clears input after submission
                namePromptTF.setText(null);
                averagePromptTF.setText(null);
                uniOptions.clearSelection();
        }
    });

    bottomPanel.add(submit);

    input.add(namePanel);
    input.add(averagePanel);
    input.add(UniversitySelectorPanel);
    input.add(submit);
    input.add(numberOfApplicants);

    return input;
}
/*******************************************END OF INPUT PANEL*/

                ///////////////////////////DISPLAY PANEL//////////////////////////

JPanel displayAllPanel() {
    JPanel displayAll = new JPanel();
    displayAll.setLayout(new BorderLayout());
    JLabel card2Title = new JLabel("DISPLAY ALL APPLICANTS");
    JTextArea displayAllApplicants = new JTextArea();

    /************************APPLICANT DISPLAY SUB PANEL*/
    JPanel applicantDisplayPanel = new JPanel();
    applicantDisplayPanel.setMinimumSize(displayAllApplicants.getPreferredSize());

    displayAllApplicants.setPreferredSize(new Dimension(275, 450));
    displayAllApplicants.setEditable(false);
    displayAllApplicants.setVisible(true);



    applicantDisplayPanel.add(card2Title);
    applicantDisplayPanel.add(displayAllApplicants);

    displayAll.add(applicantDisplayPanel, BorderLayout.CENTER);

    /**********************************************************/
    return displayAll;
}

   /**********************************************************END OF DISPLAY PANEL */


                ///////////////////////////SEARCH PANEL//////////////////////////

JPanel searchPanel() {
    JLabel card3title = new JLabel("SEARCH");
    JPanel searchPanel = new JPanel();
    searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.Y_AXIS));

    JPanel searchDisplayPanel = new JPanel();

    JTextArea searchTextArea = new JTextArea();
    searchTextArea.setMinimumSize(searchTextArea.getPreferredSize());
    searchTextArea.setPreferredSize(new Dimension(275, 450));
    searchTextArea.setEditable(false);
    searchTextArea.setVisible(true);

    searchDisplayPanel.add(searchTextArea);

    searchPanel.add(card3title);
    searchPanel.add(searchDisplayPanel);

    return searchPanel;
}
/**********************************************************END OF DISPLAY PALNEL */

/**********************************************************************************************/    
                    //ACTION LISTENER FOR CARDLAYOUT OPTIONS

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == CONTROL[0]) {
        CARD_MANAGER.first(MAIN_PAGE);
    }else if(e.getSource()==CONTROL[1]) {
        CARD_MANAGER.show(MAIN_PAGE, "Display All");
    }else if (e.getSource() == CONTROL[2]) {
        CARD_MANAGER.last(MAIN_PAGE);
    }   
}

    /**********************************************************************/ //DRIVER METHOD    
public static void main(String[] args) {
    ApplicationCentre frame = new ApplicationCentre();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(700, 500);
    frame.pack();
    frame.setVisible(true);

    }

}

  class Student {
private String FAMILYNAME;
private String AVERAGE;
private String OPTION1;
private String OPTION2;
private String OPTION3;
private ArrayList<String> CHOICES = new ArrayList();

Student (String lastName, String avrg, String Op1, ArrayList<String> hello){
    FAMILYNAME = lastName;
    AVERAGE = avrg;
    OPTION1 = Op1;
    CHOICES = hello;
}
    /********************************************************/
public String toString() {
    return FAMILYNAME+", " + "average= " + AVERAGE + ", "+ OPTION1 + ": " + "\n";

}

}

0 个答案:

没有答案