Dynamic fields addition in java/swing form

亡梦爱人 提交于 2020-01-11 06:15:08

问题


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 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.


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/4587837/dynamic-fields-addition-in-java-swing-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!