如何在JList中动态添加和删除元素?

时间:2016-07-22 19:06:00

标签: java swing nullpointerexception applet jlist

我正在研究netbeans上的java applet,并正在创建一个在线咨询系统。实际上它是我的第一个java项目,所以我实际上是一个新手。

即时通讯使用最新的java版本(8SE)和netbeans。 使用拖放方法(时间限制:|)制作GUI的组件。

工作(应该如此)如下: - 3(J)列出: - 1.大学名单 2.可用课程列表 3. 这将根据所选大学和以前的名单中的课程进行

问题我在搜索有关在JList中添加元素的任何地方,都会产生错误 我尝试使用ListModel方法,但它显示

Error:**angularbracket**identifier**angularbracket** expected

其次我也尝试过Vector方法,但它似乎也不起作用。

这是CODE

import javax.swing.*;
import java.util.Vector;

public class PrefApp extends javax.swing.JApplet {
Vector insert=new Vector();

public String selColl=null; //name of college selected from CollegeList
public String SecCour=null; //name of course selected from CourseList

public static String collegeName[];//holds the college name according to preference list made
public static String courseName[]; //holds the course name according to preference list made | works like Computer Science & Engineering~CUTCSE

public static int count=0;         //global var; used by collCode[]&courseName[] to prioritise according to preference list 

/**
 * Initializes the applet PrefApp
 */
@Override
public void init() {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PrefApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PrefApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PrefApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PrefApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                initComponents();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/**
 * This method is called from within the init() method to initialize the
 * form. WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    PageLabel = new javax.swing.JLabel();
    DescTextLabel = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    CollegeList = new javax.swing.JList<>();
    CollegeLabel = new javax.swing.JLabel();
    CoursesLabel = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    CoursesList = new javax.swing.JList<>();
    AddButton = new javax.swing.JButton();
    RemoveButton = new javax.swing.JButton();
    UpButton = new javax.swing.JButton();
    DownButton = new javax.swing.JButton();
    NoteLabel = new javax.swing.JLabel();
    jScrollPane3 = new javax.swing.JScrollPane();
    PreferenceList = new javax.swing.JList<>(insert);
    PrefListMade = new javax.swing.JLabel();
    SubmitButton = new javax.swing.JButton();

    PageLabel.setFont(new java.awt.Font("Malgun Gothic", 1, 36)); // NOI18N
    PageLabel.setText("PREFERENCE LIST");

    DescTextLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    DescTextLabel.setText("List the College & Courses of your choice according to the admission priority.");

    CollegeList.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "Amity School of Engineering & Technology, 580, Delhi", "Bhagwan Parshuram Institute of Technology, P.S.P. - 4,Sector - 17, Rohini,Delhi - 110085", "Bharti Vidyapeeth's College of Engineering, A - 4,Paschim Vihar, New Delhi - 110063", "Delhi Technical Campus, 28/1, Knowledge Park - III,Greater NOIDA, UP", "Guru Tegh Bahadur Institute of Technology,G-8 Area, Rajouri Garden, Opp. Swarg Ashram Mandir, Delhi - 110064", "HMR Institute of Technology & Management, Hameed Pur, Delhi - 110036", "JIMS Engineering Management Technical Campus,48/4, Knowledge Park - III, Greater NOIDA", "Maharaja Agrasen Institute of Technology, Sector - 22,Rohini, Delhi - 110085", "Maharaja Surajmal Institute of Technology, C - 4, Janakpuri, New Delhi - 110058", "Mahavir Swami Institute of Technology, Sonepat,Haryana (Minority Institution)", "Northern India Engineering College, FC-26, Shastri Park, Delhi - 110053", "Ambedkar Institute of Advanced Communication Technologies & Research,Geeta Colony, Delhi – 110092", "Ch. Brahm Prakash Govt. Engineering College,Behind Rao Tula Ram Hospital, Jaffarpur, New Delhi - 110073", "Delhi Institute of Tool Engineering, Okhla Industrial Area, Phase - II, Delhi - 20", "G. B. Pant Govt. Engineering College, Okhla Industrial Estate, Phase - III, Okhla, New Delhi - 110020", "National Power Training Institute, Badarpur,New Delhi" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });
    CollegeList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(CollegeList);

    CollegeLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    CollegeLabel.setText("Colleges");

    CoursesLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    CoursesLabel.setText("Courses Available");

    CoursesList.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "Computer Science & Engineering", "Information Technology", "Electronics & Communication Engineering", "Mechanical & Automation Engineering" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });
    CoursesList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane2.setViewportView(CoursesList);

    AddButton.setText("Add");
    AddButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            AddButtonActionPerformed(evt);
        }
    });

    RemoveButton.setText("Remove");

    UpButton.setText("Up");

    DownButton.setText("Down");

    NoteLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    NoteLabel.setForeground(new java.awt.Color(255, 0, 0));
    NoteLabel.setText("NOTE: Review your admission preferences carefully. Once submitted, they can't be altered!");

    PreferenceList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    PreferenceList.addContainerListener(new java.awt.event.ContainerAdapter() {
        public void componentAdded(java.awt.event.ContainerEvent evt) {
            PreferenceListComponentAdded(evt);
        }
    });
    jScrollPane3.setViewportView(PreferenceList);

    PrefListMade.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    PrefListMade.setText("Preferences of Admission");

    SubmitButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    SubmitButton.setText("Submit");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(PageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(DescTextLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(CollegeLabel)
                    .addGap(225, 225, 225)
                    .addComponent(CoursesLabel)
                    .addGap(142, 142, 142)
                    .addComponent(PrefListMade))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(UpButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(DownButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(20, 20, 20)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(NoteLabel)
                    .addGap(188, 188, 188)
                    .addComponent(SubmitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(PageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(10, 10, 10)
            .addComponent(DescTextLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(30, 30, 30)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(CollegeLabel)
                .addComponent(CoursesLabel)
                .addComponent(PrefListMade))
            .addGap(8, 8, 8)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(AddButton)
                    .addGap(7, 7, 7)
                    .addComponent(RemoveButton)
                    .addGap(107, 107, 107)
                    .addComponent(UpButton)
                    .addGap(7, 7, 7)
                    .addComponent(DownButton))
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(17, 17, 17)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(10, 10, 10)
                    .addComponent(NoteLabel))
                .addComponent(SubmitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 10, Short.MAX_VALUE))
    );
}// </editor-fold>                        

private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    String collSelected=CollegeList.getSelectedValue();  //reads value of selected college in CollegeList
    String courSelected=CoursesList.getSelectedValue();  //reads value of selected course in CoursesList

    /*UPDATION OF PREFERENCE LIST*/
    collegeName[count]=collSelected;
    if(null != courSelected)
        switch (courSelected) {
        case "Computer Science & Engineering":
            courseName[count]="CUTCSE";
            break;
        case "Information Technology":
            courseName[count]="CUTIT";
            break;
        case "Electronics & Communication Engineering":
            courseName[count]="CUTECE";
            break;
        default:
            courseName[count]="CUTMAE";
            break;
    }
    count++;    //priority variable
    /*UPDATION OF PREFEENCE LIST*/

    String choice=courSelected+"@"+collSelected;

    insert.addElement(choice);
}                                         

private void PreferenceListComponentAdded(java.awt.event.ContainerEvent evt) {                                              
    // TODO add your handling code here:
}                                             

// Variables declaration - do not modify                     
private javax.swing.JButton AddButton;
private javax.swing.JLabel CollegeLabel;
private javax.swing.JList<String> CollegeList;
private javax.swing.JLabel CoursesLabel;
private javax.swing.JList<String> CoursesList;
private javax.swing.JLabel DescTextLabel;
private javax.swing.JButton DownButton;
private javax.swing.JLabel NoteLabel;
private javax.swing.JLabel PageLabel;
private javax.swing.JLabel PrefListMade;
public javax.swing.JList<String> PreferenceList;
private javax.swing.JButton RemoveButton;
private javax.swing.JButton SubmitButton;
private javax.swing.JButton UpButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
// End of variables declaration                   
}

这是错误

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at PrefApp.AddButtonActionPerformed(PrefApp.java:222)
at PrefApp.access$100(PrefApp.java:12)
at PrefApp$4.actionPerformed(PrefApp.java:121)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Working supposed to be

JList properties | "insert" refers to the Vector variable being used

0 个答案:

没有答案