Matthew Moisen
Matthew Moisen

Reputation: 18329

MouseEvent is not Firing in JList after it's Removed and Added back to a JPanel

I have two JLists, jltCategories and jltSubcategories, belonging to the same JPanel. Double clicking on the jltCategories causes the jltSubcategories to be populated with the corresponding subcategories, and jltSubcategories is removed from the JPanel, added back and revalidated.

Double clicking the jltSubcategories AFTER it has been removed/added back does not fire anything. Yet, If I open the program and double click on the jltSubcategories, it will fire its mouse event: It will fire if it hasn't been removed/added back, but it will not fire if it has been removed/added back. Same for jltCategories: if I cause it to be removed/added, it will stop firing. Why is this so? Thank you!

jltCategories.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() > 1) {
            jbtNavigate.doClick();
        }
    }
});
jltSubcategories.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() > 1) {
            jbtLoad.doClick();
        }
    }
});
jbtNavigate.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String catName = jltCategories.getSelectedValue();
        try {
            jpLists.remove(jltSubcategories);
            jltSubcategories = new JList<String>(SQL.populateSubcategories(catName));
            jpLists.add(jltSubcategories);
            jpLists.revalidate();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
});
jbtLoad.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
             System.out.println("Testing Testing 213");
        }
});

Upvotes: 2

Views: 176

Answers (1)

trashgod
trashgod

Reputation: 205875

It is not enough to revalidate() the view; you must also let the model notify the view that new data is available.

DefaultListModel  model = (DefaultListModel ) jltSubcategories.getModel();
model.fireContentsChanged(0, model.getSize());

If this is ineffective, please edit your question to include an sscce that exhibits the problem you describe.

Addendum: It's not clear why you use a MouseListener to effect the update; use a ListSelectionListener, shown here.

Upvotes: 3

Related Questions