In our Swing application, we are using an automated testing tool in QA (Qf-Test) that works better when the swing components are named. (calling Component.setName). Although their automatic name assignments work reasonably well, we are introducing SwingX components into the project and that is causing some issues for the tool.
There are a lot of potential components on a screen (your typical business app data entry screens, but a lot of them - the app is on the complexity level of an ERP), what options are ther开发者_开发技巧e for naming swing components in a reasonably unobtrusive manner?
I typically store the fields in a JPanel in properties on the JPanel, like this:
private JLabel firstNameLabel; private JTextField firstNameTextField;
At the end of the routine that instantiates and lays out these components, you could run a routine that uses java.lang.reflect
to loop through each property of the panel. If a property descends from the class Component
, you can call setName
on it with the name of the property. So for example, it would end up calling:
this.firstNameLabel.setName("firstNameLabel"); this.firstNameTextField.setName("firstNameTextField");
...except through java.lang.reflect
You could also have the routine examine the bumpy case names of variables and replace it with standard case with spaces. This would make them more readable.
This approach will ensure that no matter what components you add to a panel, they will all get friendly names.
I generally use a compound name for all my components; the name is built upon the parent name (eg a JDialog
) and the field name (obtained by reflection). That makes component names unique in most cases (you still may have conflicts depending on how you name parents and how you use them, e.g. if you open several JInternalFrame
and all have the same name...)
I have implemented a generic naming strategy (that does just that) in Guts-GUI.
By the way, component naming is not only interesting for UI testing, but it may also be useful for resource injection strategies (i18n of components).
How are you building the interface? JFormDesigner and probably most of the other editors allow to set the name of the component automatically, which is very handy. Most of the time I don't have to think about the component names at all. Only exceptions are components that are not placed with JFormDesigner.
精彩评论