0

Right now, when I have a form with many JComponents, mainly JTextFields, JTextAreas, JComboboxes, JCheckBoxes and JButtons and want to control their behaviour, for instance the change of focus after a certain key was released, I do the following:

I put all my components in a JComponent[] and cycle through it, adding the appropriate listener. When an event is registered by said listener, I check with "instanceof" what kind of JComponent fired the event and assign the proper reaction.

I use this method for instance to cycle with VK_ENTER through the form, or to "firePropertyChange(..)" after a DocumentListener fires, or to add UndoRedoListeners and so on.

My question : is there a better way to do this and if yes, can you explain to me the benefits ?

4

2 回答 2

1

but my question refers to the general practice of putting all JComponents in an array and cycling through them for every listener and every fired event. It works fine enough, but it feels a bit "uneconomic",so I wanted to know if it is recommended practice, or if there is a better way of doing it.

I usually write a custom listener (often as an anonymous class) per type/ instance if I have type/ instance specific behavior so that I can avoid instanceof and other other checks.

于 2012-11-12T09:01:10.123 回答
1

You'll want to customise the focus tranfersal system.

Take a look at How to Use the Focus Subsystem, in particular Customizing Focus Traversal

于 2012-11-12T09:25:14.003 回答