1

I'm making a To-Do List application and I have a PrimaryList frame and a SubList frame. When a user selects something from the PrimaryList (Grocery...or something like that) and then hits a forward arrow JButton, it is supposed to launch up the SubList frame. Now here is what I have for the actionPerformed method of the forward arrow button called btnArrow.

private void btnArrowActionPerformed(java.awt.event.ActionEvent evt) {                                         
    lstToDoLists.addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent e){
            if (lstToDoLists.getSelectedIndex() > 0){
                btnArrow.addActionListener(new ActionListener(){
                    public void actionPerformed (ActionEvent ae){
                        if (btnArrow==ae.getSource()){
                            SubList sublist = new SubList();
                            sublist.setVisible(true);
                        }
                    }
                });
            }
        }            
    });
}

Now, when I run the PrimaryList file and click on an item in my JList and then select the forward arrow button, I get nothing. But then when I click another element from the list and press the forward arrow button again, my SubList pops up twice.

Something isn't write with what I've written and I am hoping someone else will know how to fix this problem.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
P_Drach
  • 121
  • 6

1 Answers1

4

You're adding listeners inside of listeners -- something that you don't want to do, since this means that new listeners will be added, each time an event occurs.

Solution: don't add listeners inside of other event listeners but rather add the listeners once and in your code's constructor or initialization method.

Note that I would not use a ListSelectionListener at all. Instead I'd just use a single ActionListener on the button. Then in that listener, get the list's selection and use it.

e.g.,

private void btnArrowActionPerformed(java.awt.event.ActionEvent evt) {  
    // if list contains String:
    String selectedItem = (String) lstToDoLists.getSelectedItem();

    // check that selectedItem isn't null, i.e, 
    if (selectedItem != null) {
        // TODO: do something with selection here
    }
}

As a side recommendation, please look at The Use of Multiple JFrames, Good/Bad Practice?.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373