问题描述:

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 ?

网友答案:

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.

网友答案:

You'll want to customise the focus tranfersal system.

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

相关阅读:
Top