单击按钮时无法刷新 JPanel
我是 java swing 的新手,在刷新面板时遇到问题。 你能告诉我为什么点击按钮后,JTextField 没有显示在主面板中吗? 提前致谢:)
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
javax.swing.JTextField t = new javax.swing.JTextField("Hello");
mainPanel.add(t);
mainPanel.validate();
}
I'm new in java swing and I have a problem with refreshing my panel.
Can you tell me why after clicking on button , the JTextField doesn't show in mainpanel?
Thanks in advance:)
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
javax.swing.JTextField t = new javax.swing.JTextField("Hello");
mainPanel.add(t);
mainPanel.validate();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过调用 revalidate() 而不是 validate()?
Have you tried calling revalidate() instead of validate()?
这是我愚蠢的疯狂猜测:您正在使用 NetBeans 构建 GUI,而应该接受新 JTextField 的容器(mainPanel)使用 NetBeans 的 GroupLayout,这是一种很难容纳在飞。如果是这样,让 mainPanel 使用更用户友好的布局,或者嵌套容器,每个容器都使用自己的简单布局,以实现复杂的 GUI。
您需要在此处阅读有关如何使用这些布局管理器的信息:布局out Components in a Container
您还需要在本问题和下一个问题中提供足够的信息,以便我们不必继续制作 SWAG。
Here's my silly wild @ss guess: you're using NetBeans to build your GUI and the container that is supposed to accept the new JTextField, the mainPanel, uses NetBeans' GroupLayout, one that has a great deal of difficulty accommodating components added on the fly. If so, have mainPanel use a more user-friendly layout, or nest containers each using its own simple layout in order to achieve a complex GUI.
You'll want to read up on how to use these layout managers here: Laying out Components in a Container
You'll also want to provide enough information in this and your next questions so that we don't have to keep making SWAGs.
您可能忘记设置
mainPanel
的布局?请尝试以下操作:
更新:
上述建议不够聪明。
正如 camickr 指出的,
FlowLayout
是JPanel
的默认布局。我希望以下建议会更有帮助。
例如,对情况进行建模。
结论:如果您的面板尺寸太小,您必须手动调整其尺寸,才能看到添加的 JTextField 实例。
You possibly forgot to set the layout of the
mainPanel
?Try the following:
UPDATE:
The above suggestion was not clever enough.
As camickr pointed,
FlowLayout
is the default layout forJPanel
.The following suggestion will be more helpful, I hope.
Example, modelling the situation.
Conclusion: if the size of your panel is too small, you have to resize it manually, to see the added JTextField instance.