简体   繁体   中英

How do I add components at run time to a Swing UI created with Netbeans visual editor?

I am currently writing an application where the user has, at some point, to click a button which have been generated at run time. I know how to do it when writing all my swing code from scratch, but I'd like to take advantage of Netbeans' visual editor.

The generated UI code goes into an initComponents() method I can't modify since it is regenerated automatically from the visual form.

I'd like to have a panel I place at design time using the visual editor in which I could add the buttons at run time so that they fit nicely in the layout, but I don't know how to access the panel in a convenient way. Besides, there may be another method than using a panel.

So basically :

  • How do I locate a Swing component at run time ?
  • Is there a better way of integrating components created at run time in a generated Swing UI ?

Thanks for your help.

NetBeans-generated GUI classes store all the components in private variables. You can add a method into the generated class that returns the panel, and it will remain even as you do additional design.

If you're going to use a generated UI, then it's probably best to use a JPanel within that UI to "carve out" space for your own components. Otherwise, you'll have to worry about how your components affect the layout of the components placed by the UI.

Just because you are using NetBeans generated GUI classes doesn't mean that you have to use the Group layout for the panels. I find that switching it to a BorderLayout helps especially in cases where I want to add some dynamic user interface code.

It is possible to change private to protected/public by either right clicking on a component in the GUI-Designer, choosing properties and hitting the Source-tab or right clicking on a component and choosing "Modify Source" (or something like that) and setting the appropriate access modifier. Or just export them via a getXYZComponent() method.

Locating the component should provide as being too difficult, as you built it with the designer and thus know each component. For example, if you had a JTabbedPane and wanted to add tabs to it when the user hits a button or something like that, you would simply issue myJTabbedPane.add(myCustomComponent); et voila, a new tab appears.

It is also possible to modify the auto-generated code and/or the code used for auto-generation by using the "Modify source" dialog mentioned above, which can be really useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM