Java:从List选择侦听器获取结果

时间:2013-06-20 06:26:26

标签: java netbeans-7 jlist listselectionlistener

我的列表选择监听器有一些问题,我在下面给你看 1.听众打印两次的结果,我对它一无所知......!??!为什么打印两次? 2.当我按下searchBt并且结果显示时,我选择了一个结果我想从valueChanged(ListSelectionEvent e)返回ChooseIndex但是它不能有一个return语句并且所选的thge j列表的索引是无用的......问题是什么?

public class SearchPage extends javax.swing.JFrame {

public SearchPage() {
    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() {

    SearchBox = new javax.swing.JTextField();
    SearchBt = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    SearchBt.setText("Search");
    SearchBt.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            SearchBtActionPerformed(evt);
        }
    });

    jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    jList1.setToolTipText("");
    jList1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    jList1.setSelectionBackground(new java.awt.Color(102, 0, 102));
    jList1.setValueIsAdjusting(true);
    jList1.setVerifyInputWhenFocusTarget(false);
    jScrollPane1.setViewportView(jList1);
    jList1.getAccessibleContext().setAccessibleName("");

    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(16, 16, 16)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(SearchBt, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(281, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(125, 125, 125)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(SearchBt))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
            .addContainerGap())
    );

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

private void SearchBtActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String tag = SearchBox.getText().trim();
    Vector<String> vector = new Vector<String>();
    for (int i = 0; i <Code.CodeSearch(tag).size(); i++) {
        String string = Code.FNameExtractor(Code.CodeSearch(tag).get(i).getFileName())+" Uploaded By "+Code.CodeSearch(tag).get(i).getUserdetails().getUsername();
        vector.add(string);            
    }
    jList1 = new JList<String>(vector);
    ListSelectionModel listSelectionModel = jList1.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(jList1);
}                                        

/**
 * @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(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SearchPage.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 SearchPage().setVisible(true);
        }
    });
}
            class SharedListSelectionHandler implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) { 
        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
        int ChooseIndex =lsm.getMaxSelectionIndex();
        System.out.println(ChooseIndex);
    }
}
// Variables declaration - do not modify                     
private javax.swing.JTextField SearchBox;
private javax.swing.JButton SearchBt;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   
}    

1 个答案:

答案 0 :(得分:1)

选择侦听器仅告诉我们所选项目的索引。这很正常。该列表不关心内容。您必须在某处存储列表模型(iaw,实际显示的字符串列表),并使用侦听器中的索引值来查找模型中索引处的内容。这是常见的模式。

对于第一个问题 - 我在print语句上设置了一个断点,调试并查看堆栈跟踪。然后我会明白为什么这个方法被调用了两次。