将组件动态添加到 JDialog [英] Dynamically Add Components to a JDialog
问题描述
当用户单击 JDialog 上的按钮时,我无法将 JComponent 添加到 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屋!