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

标签 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                   
}    

最佳答案

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

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

关于Java:从列表选择监听器获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17206652/

相关文章:

java - 设置可滚动列表的边界

java - 如果将 SSID/网络名称与字符串匹配的语句不起作用

java - 如何最好地为未存储在数据库中的对象生成 key ?

java - java调试中是否可以在外部完成线程?

C++生成随机数-1

java - 将 MP3 播放列表保存到文件

java - 如何动态添加项目到 JList?

java - Java中的不合格名称

java - EJB 注入(inject) Restful 服务(NullPointerException)

Ruby 在Netbeans 7 中被删除,如何在Netbeans7 中使用它?