3.7. Client PropertiesIn addition to its normal set of properties, JComponent includes a hashtable in which it can store arbitrary name/value pairs. These name/value pairs are called client properties, and they can be set and queried with the putClientProperty() and getClientProperty() methods. Since these are JComponent methods, they are inherited by all Swing components. Although both the name and value of a client property can be arbitrary objects, the name is usually a String object. Client properties allow arbitrary data to be associated with any Swing component. This can be useful in a number of situations. For example, suppose you've created a JMenu that contains 10 JMenuItem components. Each component notifies the same ActionListener object when it is invoked. This action listener has to decide which of the 10 menu items invoked it and then perform whatever action is appropriate for that menu item. One way the action listener can distinguish among the menu items is by looking at the text that each displays. But this approach doesn't work well if you plan to translate your menu system into other languages. A better approach is to use the setActionCommand() method (inherited from AbstractButton) to associate a string with each of the JMenuItem components. Then the action listener can use this string to distinguish among the various menu items. But what if the action listener needs to check some kind of object other than a String in order to decide how to process the action event? Client properties are the solution: they allow you to associate an arbitrary object (or multiple objects) with each JMenuItem. Client properties are used within Swing to set properties that are specific to a single look-and-feel implementation. For example, the default Java look-and-feel examines the client properties of a few components to obtain additional information about how it should display the components. Here are some details on these particular client properties:
Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|