簡體   English   中英

Java JList,允許用戶單擊值並打開新的jframe

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

該代碼具有一個稱為Colleges的類,該類帶有一個組合框,該框允許用戶選擇他/她想從哪些州查看大學,我必須這樣做,以便當用戶單擊列表中的一所大學時將其帶到新的JFrame以及有關大學的信息。

第一個代碼是我的大學班級:

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;              

}

其次是我的狀態類,這是列表:

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”,對其他州。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM