Java 允许用户点击一个值并打开一个新的 jframe 的 JList

Java JList that allows the user to click on a value and open a new jframe

该代码有一个名为 colleges 的 class,它带有一个组合框,允许用户选择 he/she 想要查看哪个州的大学,我必须在用户点击时做到这一点在列表中的一所大学上,它将他们带到一个新的 JFrame 中,其中包含有关该大学的信息。

第一个代码是我的大学Class:

public class Colleges extends javax.swing.JFrame {

/**
 * Creates new form Colleges
 */
public Colleges() {
    initComponents();
}

/**
 * This method is called from within the constructor 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() {

    jLabel1 = new javax.swing.JLabel();
    jComboBox1 = new javax.swing.JComboBox<>();
    jButton2 = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    jLabel1.setText("Select which state you wish to view colleges from.");

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { null, "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }));
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBox1ActionPerformed(evt);
        }
    });

    jButton2.setText("Close");
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton2MouseClicked(evt);
        }
    });

    jButton1.setText("Next");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton1MouseClicked(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(47, 47, 47)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1))
            .addContainerGap(74, Short.MAX_VALUE))
        .addGroup(layout.createSequentialGroup()
            .addComponent(jButton2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton1))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 213, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton2)
                .addComponent(jButton1)))
    );

    pack();
}                        
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
    System.exit(0);
}                                     
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      

}                                     
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (jComboBox1.getSelectedItem() == "Alabama"){
        Alabama s = new Alabama();
        s.setVisible(true);
        s.pack();
        s.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Alaska"){
        Alaska AK = new Alaska();
        AK.setVisible(true);
        AK.pack();
        AK.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Arizona"){
        Arizona AZ = new Arizona();
        AZ.setVisible(true);
        AZ.pack();
        AZ.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Arkansas"){
        Arkansas AR = new Arkansas();
        AR.setVisible(true);
        AR.pack();
        AR.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "California"){
        California CA = new California();
        CA.setVisible(true);
        CA.pack();
        CA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Colorado"){
        Colorado CO = new Colorado();
        CO.setVisible(true);
        CO.pack();
        CO.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Connecticut"){
        Connecticut CT = new Connecticut();
        CT.setVisible(true);
        CT.pack();
        CT.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Delaware"){
        Delaware DE = new Delaware();
        DE.setVisible(true);
        DE.pack();
        DE.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Florida"){
        Florida FL = new Florida();
        FL.setVisible(true);
        FL.pack();
        FL.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Georgia"){
        Georgia GA = new Georgia();
        GA.setVisible(true);
        GA.pack();
        GA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Hawaii"){
        Hawaii HI = new Hawaii();
        HI.setVisible(true);
        HI.pack();
        HI.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Idaho"){
        Idaho ID = new Idaho();
        ID.setVisible(true);
        ID.pack();
        ID.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Illinois"){
        Illinois IL = new Illinois();
        IL.setVisible(true);
        IL.pack();
        IL.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Indiana"){
        Indiana IN = new Indiana();
        IN.setVisible(true);
        IN.pack();
        IN.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Iowa"){
        Iowa IA = new Iowa();
        IA.setVisible(true);
        IA.pack();
        IA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Kansas"){
        Kansas KS = new Kansas();
        KS.setVisible(true);
        KS.pack();
        KS.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Kentucky"){
        Kentucky KY = new Kentucky();
        KY.setVisible(true);
        KY.pack();
        KY.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Louisiana"){
        Louisiana LA = new Louisiana();
        LA.setVisible(true);
        LA.pack();
        LA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Maine"){
        Maine ME = new Maine();
        ME.setVisible(true);
        ME.pack();
        ME.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Maryland"){
        Maryland MD = new Maryland();
        MD.setVisible(true);
        MD.pack();
        MD.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Massachusetts"){
        Massachusetts MA = new Massachusetts();
        MA.setVisible(true);
        MA.pack();
        MA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Michigan"){
        Michigan MI = new Michigan();
        MI.setVisible(true);
        MI.pack();
        MI.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Minnesota"){
        Minnesota MN = new Minnesota();
        MN.setVisible(true);
        MN.pack();
        MN.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Mississippi"){
        Mississippi MS = new Mississippi();
        MS.setVisible(true);
        MS.pack();
        MS.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Missouri"){
        Missouri MO = new Missouri();
        MO.setVisible(true);
        MO.pack();
        MO.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Montana"){
        Montana MT = new Montana();
        MT.setVisible(true);
        MT.pack();
        MT.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Nebraska"){
        Nebraska NE = new Nebraska();
        NE.setVisible(true);
        NE.pack();
        NE.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Nevada"){
        Nevada NV = new Nevada();
        NV.setVisible(true);
        NV.pack();
        NV.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "New Hampshire"){
        New_Hampshire NH = new New_Hampshire();
        NH.setVisible(true);
        NH.pack();
        NH.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "New Jersey"){
        New_Jersey NJ = new New_Jersey();
        NJ.setVisible(true);
        NJ.pack();
        NJ.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "New Mexico"){
        New_Mexico NM = new New_Mexico();
        NM.setVisible(true);
        NM.pack();
        NM.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "New York"){
        New_York NY = new New_York();
        NY.setVisible(true);
        NY.pack();
        NY.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "North Carolina"){
        North_Carolina NC = new North_Carolina();
        NC.setVisible(true);
        NC.pack();
        NC.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "North Dakota"){
        North_Dakota ND = new North_Dakota();
        ND.setVisible(true);
        ND.pack();
        ND.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Ohio"){
        Ohio OH = new Ohio();
        OH.setVisible(true);
        OH.pack();
        OH.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Oklahoma"){
        Oklahoma OK = new Oklahoma();
        OK.setVisible(true);
        OK.pack();
        OK.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Oregon"){
        Oregon OR = new Oregon();
        OR.setVisible(true);
        OR.pack();
        OR.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Pennsylvania"){
        Pennsylvania PA = new Pennsylvania();
        PA.setVisible(true);
        PA.pack();
        PA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Rhode Island"){
        Rhode_Island RI = new Rhode_Island();
        RI.setVisible(true);
        RI.pack();
        RI.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "South Carolina"){
        South_Carolina SC = new South_Carolina();
        SC.setVisible(true);
        SC.pack();
        SC.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "South Dakota"){
        South_Dakota SD = new South_Dakota();
        SD.setVisible(true);
        SD.pack();
        SD.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Tennessee"){
        Tennessee TN = new Tennessee();
        TN.setVisible(true);
        TN.pack();
        TN.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Texas"){
        Texas TX = new Texas();
        TX.setVisible(true);
        TX.pack();
        TX.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Utah"){
        Utah UT = new Utah();
        UT.setVisible(true);
        UT.pack();
        UT.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Vermont"){
        Vermont VT = new Vermont();
        VT.setVisible(true);
        VT.pack();
        VT.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Virginia"){
        Virginia VA = new Virginia();
        VA.setVisible(true);
        VA.pack();
        VA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Washington"){
        Washington WA = new Washington();
        WA.setVisible(true);
        WA.pack();
        WA.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "West Virginia"){
        West_Virginia WV = new West_Virginia();
        WV.setVisible(true);
        WV.pack();
        WV.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Wisconsin"){
        Wisconsin WI = new Wisconsin();
        WI.setVisible(true);
        WI.pack();
        WI.setLocationRelativeTo(null);
        this.dispose();
    }
    if (jComboBox1.getSelectedItem() == "Wyoming"){
        Wyoming WY = new Wyoming();
        WY.setVisible(true);
        WY.pack();
        WY.setLocationRelativeTo(null);
        this.dispose();
    }
}                                          
public static void main(String args[]) {
    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(Colleges.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Colleges.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Colleges.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Colleges.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Colleges().setVisible(true);
        }
    });
}                   
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;              

}

第二个是我的 class 州,这是列表所在的位置:

public class Alabama extends javax.swing.JFrame {

/**
 * Creates new form Alabama
 */
public Alabama() {
    initComponents();
}

/**
 * This method is called from within the constructor 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() {

    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList<>();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("     Top 5 Colleges in Alabama");

    jList1.setModel(new javax.swing.AbstractListModel<String>() {
        String[] strings = { "Samford University", "University of Mobile", "Huntingdon College", "Tuskegee University", "Oakwood University" };
        public int getSize() { return strings.length; }
        public String getElementAt(int i) { return strings[i]; }
    });
    jScrollPane1.setViewportView(jList1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(75, 75, 75))
        .addGroup(layout.createSequentialGroup()
            .addGap(100, 100, 100)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(100, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(109, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* 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(Alabama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Alabama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Alabama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Alabama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Alabama().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   

针对您的主要问题: 像这样添加一个 ListSelectionListener:

jList1.addListSelectionListener(new ListSelectionListener()
{
    public void valueChanged(ListSelectionEvent event)
    {
        String markedState = jList1.getSelectedValue();
        //... create your new JFrame
    }
});

正如@MadProgrammer 所说,将您的字符串与 .equals() 而不是“==”进行比较 如果我没看错,不用每次都用 "if" 询问,你可以为阿拉巴马州做 "if",为其他州做 "else if"。