1

I have a JPanel that uses a FlowLayout and contains many JButtons. The buttons are in a 2-dimensional grid (by the FlowLayout). The JPanel can be resized, and, of course, when it is, the location of the buttons in the grid changes (although the order, of course, stays the same). I want the user to be able to navigate from one button to another in the grid by using the arrow keys on the keyboard.

Is there a way to tell for a given button, which button is currently directly above it, which button is directly below it, and which buttons are to its immediate left and right?

Obviously, this would be trivial if I were using a GridLayout, but I need to use a FlowLayout for other reasons.

Paul Reiners
  • 8,576
  • 33
  • 117
  • 202

2 Answers2

2

The left and right arrow keys are not an issue. As mentioned by jzd you just add the KeyStrokes to the set of traversal keys.

For the up/down keys you will need to create a custom Action. You can use the location of the current component. Then to go up you can change the Y coordinated by say 10 pixels (5 pixels for the row gap between components pluse an extra 5). Then you can use the:

Container.getComponentAt(Point p) 

to find the component at that new location.

To go down you would start with the location of the button then add on the height of the button plus 10 pixels.

Of course you would then use Key Bindings to bind the up/down KeyStroke to the Action.

Note: I'm not sure if you need to add the 5 extra pixels to find the componen above or below the component. You may just be able to use the vertical gap. I'm just not sure how the boundary checking works on the getComponentAt() method.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

I think you can just use focus travel implementation that is in place as tab or shift navigates the selected buttons in a FlowLayout correctly.

I think you just need to add the arrow keys to sets like the forwardDefaultFocusTraversalKeys

More info:

http://download.oracle.com/javase/tutorial/uiswing/misc/focus.html

jzd
  • 23,473
  • 9
  • 54
  • 76