Dynamic fields addition in java/swing form
I'm pretty new to java, and using netbeans for design a UI.
What I am trying to do is...
in the form. there are a jComboBox and a JTextField, where user can input the service he is choosing and an observation. So far so good. JComboBox is populated from database entries.
The problem is, a user can input N different services at once (there are too 开发者_JS百科much to be a bunch of checkboxes). I was thinking into add a "[+]" button (along with a "[-]" for removal). Thus, users click on [+] and another new line with a jcombobox + jtextfield appear right below the previous ones.
I'm stucked at this point. On [+] button ActionPerformed I just can't clone and add previous nodes. Any idea on how proceed.
My background is webdev. Doing this with javascript would be really quick. Well, I think you already know what I'm trying to do. Waiting for some light. Thx.
You're on the right track. Here's some source code to give you some ideas
The basic idea is that the EntryList is responsible for keeping track of the rows to display; each row has a plus/minus button, and then delegates out the actual adding/removing to this EntryList. It also exposes methods to disable the minus/plus button so that the list view can ensure that you don't remove a single entry (so that you don't have an empty display)
This doesn't work perfectly; you'll notice you need to resize the frame to get the new rows to show up correctly. But this should be enough to get you started.
Create your main panel to use a layout manager that displays component horizontally. The Box class is easy to use for this. Then you just create a new panel with the components you want to display and add this panel to your main panel. Something like:
JComboBox checkBox = new JComboBox(...);
JTextField textField = new JTextField(...);
JPanel row = new JPanel();
row.add( comboBox );
row.add( textfield );
mainPanel.add( row );
mainPanel.revalidate();
精彩评论