NetBeans 表单设计器:调用 initComponents 后更改布局
我有一个扩展 javax.swing.JPanel 的类,它包含一个 JButton。我已在 NetBeans 设计器 中创建了该类。因此,我有一个从类构造函数调用的 initComponents()
函数。
我想做的是当/如果调用函数时,我想添加第二个按钮,并更改两个按钮的布局。简单地做:
public void addSecond() {
javax.swing.JButton secondButton = new javax.swing.JButton();
add(secondButton , java.awt.BorderLayout.CENTER);
}
不起作用,新按钮不显示。我也尝试调用 invalidate()
但没有成功。
- 如何触发布局的重新评估?
- 如果多次调用所述函数,我需要在布局/按钮的哪些部分调用 dispose() ?我还需要担心其他清理工作吗?
- 如果我不使用 NetBeans 设计器,这会更容易处理吗?
I have a class that extends javax.swing.JPanel
, it contains a single JButton. I've created the class in NetBeans designer. As such, I have a initComponents()
function thats called from the class constructor.
What I want to do is when/if a function is called, I want to add a second button, and change the layout of the two buttons. Doing simply:
public void addSecond() {
javax.swing.JButton secondButton = new javax.swing.JButton();
add(secondButton , java.awt.BorderLayout.CENTER);
}
Doesnt work, the new button doesnt show up. I tried a call to invalidate()
as well but no luck.
- How do I trigger a re-evaluation of the layout?
- If said function is called more than once, what parts of the layout/buttons do I need to call dispose() on? Any other cleanup I should worry about?
- Would this be easier to handle if I don't use the NetBeans designer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在使用
BorderLayout.CENTER
添加按钮之前,您需要设置面板的布局。此外,您还必须删除并再次添加第一个按钮,并调用面板上的revalidate()
方法。如下更改您的 addSecond() 方法,它应该可以工作。
You need to set the layout of the panel before you add the button with
BorderLayout.CENTER
. Also, you must remove and add the first button again and invoke therevalidate()
method on the panel.Change your addSecond() method as below and it should work.
当您以改变布局的方式更改组件时,您需要通过调用
revalidate()
再次触发布局管理器。您可以根据需要多次调用它。对于简单的布局,只需调用
repaint()
就足够了。实际上,除非您要动态更改面板(即动态添加/删除组件),否则您应该使用 netbeans 设计器,这样所有 Swing 元素都位于一处。
-- 编辑 --
每个面板只能将一个组件放入BorderLayout.CENTER中。如果将多个元素放入面板的同一位置,则绘制的内容没有明确定义,即它可能是其中一个元素(或两者)。
when you changed the components in a way that changes the layout, you need to trigger the layout manager again by calling
revalidate()
. You can call it as often as you want.For simple layouts just calling
repaint()
may be sufficient.And actually unless you're doing dynamically changing panels (i.e. adding/removing components on the fly) you should use the netbeans designer, so all the Swing elements are in one place.
-- EDIT --
And you can only put one component into BorderLayout.CENTER per panel. If you put more than one element into the same position of a panel, what gets painted is not well defined, i.e. it may be either of the elements (or both).