Question

i've some problem with my list selection listener that i show you below 1.the result of the listener printing twice that i don't have an idea about it...!??!why it's printing twice? 2.when i pressing the searchBt and the result shows,and i choose one of the result i want to return ChooseIndex from the valueChanged(ListSelectionEvent e) but it can't has a return statement and the selected index of thge j list is useless...what's the problem?

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                   
}    
Was it helpful?

Solution

The selection listener only tells us the index of the selected item. That's normal. The list doesn't care about the content. You have to store the list model (iaw, a list of strings that you actually display) somewhere and use the index value from the listener to lookup the content at the index in your model. That's the common pattern.

For the first question - I'd set a breakpoint on the print statement, debug and look at the stacktrace. Then I'd see why the method was called twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top