0

I am displaying a JList that contains file names, in a JScrollPane. I want to select files either by clicking on a line, or by using the up and down keys.

Using the mouse works fine, but if I select one line, then click "down" or "up", it skips one entry, and selects the next line but one. I thought maybe the key was bouncing, but there is only one key event per key stroke.

I keep adding traces to the code, but I just can't see my problem!

Do I need to do something with the ListModel? Help is much appreciated!

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Paul Morrison
  • 1,694
  • 3
  • 20
  • 35
  • 5
    If you don't get a decent answer soon, consider creating and posting an [sscce](http://sscce.org). Let's work with real code if possible. – Hovercraft Full Of Eels Feb 24 '13 at 03:24
  • @PaulMorrison: I've cited a reference implementation below and listed a few things to check. – trashgod Feb 24 '13 at 03:42
  • 1
    by default, up/down keys are bound to moving the selection to the previous/next: nothing to do on your part – kleopatra Feb 24 '13 at 11:10
  • @kleopatra - Of course - that explains everything - thanks a million! However, thanks also, trashgod - ListSelectionListener was part of the answer as well! So it's working great now! I will answer my question below. – Paul Morrison Feb 24 '13 at 15:39

2 Answers2

3

You might compare your approach to this working example that uses a ListSelectionListener. In particular check your use of getValueIsAdjusting(). Also verify that you do not interfere with the existing key bindings, and do not add an unecessary KeyListener. This variation is pictured below.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

I just wanted to make sure this question is officially answered... Kleopatra pointed out that up and down keys are handled automatically, which explains why I was skipping entries. In addition, I added a ListSelectionListener (suggested by trashgod) to add some application-specific logic to the key handling. Thanks to both of you!

Paul Morrison
  • 1,694
  • 3
  • 20
  • 35