Mice and keyboards in Swing

This listener works 95% of the time:

    messagesJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
        public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
            messagesJListValueChanged(evt);
        }
    });

however, he will someday register at an inconvenient time. Undoubtedly, my error handling is the main problem. That being said, there is an alternative listener that combines different listeners of the mouse and keyboard, but only those events?

+1
source share
2 answers

I just combined:

private void messagesJListKeyReleased(java.awt.event.KeyEvent evt) {
    userSelectedRow();
}

private void messagesJListMouseReleased(java.awt.event.MouseEvent evt) {
    userSelectedRow();
}

so only if the user actually clicks the mouse or keyboard, the userSelectedRow () method is called.

0
source

This listener works 95% of the time:

works for me in all cases, be sure to check if selectedItem, Index or Rowmore than-1 (no selection)

    jList.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = jList.getSelectedIndex();
                if (selectedRow> -1) {
                    System.out.println("selection");
                }                    
            }
        }
    });
+3
source

All Articles