Java:从列表选择监听器获取结果



我的列表选择侦听器有一些问题,我将在下面展示给您1.监听器打印两次的结果,我都不知道…?? ?!为什么要打印两次?2.当我按下searchBt和结果显示,我选择的结果之一,我想从valueChanged(ListSelectionEvent e)返回ChooseIndex,但它不能有一个返回语句和这些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                   
}    

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

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

最新更新