FaqMatisseAddDynamicComponents

How can I dynamically create a variable number of GUI components?

How can I create multiple JButtons with a GridLayout? The number of these components stays in a variable parameter.

Answer:

Creating a wizard or a visual tool to generate dynamic GUIs is pretty complex -- in any case, the user will have to write some of the code that provides the dynamic content. NetBeans GUI builder does not provide any assistance in this regard.

Workaround

  • The standard workaround is to create only an empty panel in the GUI builder, and fill it at runtime from user written code.
  • It is also possible to write a special container bean ( JPanel subclass) that defines the layout programmatically - this is basically a reusable version of the method described above. Having specialized "layout" components is probably the best way from the GUI builder integration point of view.
  • Another possibility is to use placeholder components in the GUI form and replace them with real components in runtime. This is possible if the number of components is known in advance (or is not bigger than a certain number). Then you use GroupLayout's 'replace' method. Disadvantage: Redundant components are instantiated in the UI, then replaced, but it could work in some situations.
  • If all the components are known in advance and they only need to be shown/hidden based on some user actions, then it is usually possible to have them all in the GUI form and just call setVisible(true/false) on them appropriately at runtime.

  Applies to: All Netbeans Versions
  Platforms: All
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo