动态添加组件到JDialog [英] Dynamically Add Components to a JDialog
问题描述
当用户单击JDialog上的按钮时,我无法将JComponents添加到JDialog。基本上我希望它看起来像这样:
I am having trouble adding JComponents to a JDialog when the user clicks a button on the JDialog. Basically I want it to look like this:
然后,当用户点击添加新字段时,我希望它看起来像这样:
Then, when the user clicks "Add New Field" I want it to look like this:
我似乎无法获得添加新JLabel或JTextField的对话框。任何人都可以指出我正确的方向吗?
I cannot seem to get the dialog to add the new JLabel or JTextField. Can anyone point me in the right direction?
编辑:这是添加新字段按钮的操作(只是尝试标签现在)。
EDIT: This is the action for the "Add New Field" button (Just trying a label now).
@Action
public void addNewField()
{
Container contentPane = getContentPane();
JLabel label = new JLabel ("welkom");
contentPane.add(label, BorderLayout.CENTER);
}
解决方案:
我使用了mre的解决方案并让它发挥作用。这是我的最终功能:
I used mre's solution and got it to work. Here is my final function:
@Action
public void addNewField()
{
System.out.println("New Field...");
Container contentPane = getContentPane();
JLabel label = new JLabel ("welcome");
label.setBounds(10,10,100,10); //some random value that I know is in my dialog
contentPane.add(label);
contentPane.validate();
contentPane.repaint();
this.pack();
}
我的另一个问题是我使用的是免费设计布局在NetBeans中,这意味着我的标签可能处于某种奇怪的位置,而不是在我的对话框中(只是一个猜测)。我用 label.setBounds()
解决了这个问题,以便它显示我想要的确切位置。
Another one of my problems is that I am using a "Free Design" layout in NetBeans, which meant that my label was probably in some weird position rather than being in the bounds of my dialog (just a guess). I solved this problem with label.setBounds()
so that it showed exactly where I wanted it to.
推荐答案
从容器中动态添加/删除组件时,需要调用 revalidate()
/ validate()
和 repaint()
。前者将强制容器再次布局其组件,后者将删除任何视觉工件。
When dynamically adding/removing components from a container, it's necessary to invoke revalidate()
/validate()
and repaint()
afterward. The former will force the container to layout its components again and the latter will remove any visual "artifacts".
这篇关于动态添加组件到JDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!