关于使用 JPanels 的 Java 简单问题
这里只是一个简单的问题。我有一个程序,需要在其中创建许多 JPanel,然后每个 JPanel 都包含一些对象(通常是 JLabels)。
每次创建新的 JPanel 时,我都必须执行一些操作,我想知道执行这些操作的顺序是否有任何影响,或者是否有标准做法。
我所做的操作如下:
声明 JPanel:JPanel panel = new JPanel(...)
声明 JLabel:JLabel laberl = new JLabel...
将 JPanel 添加到其他内容窗格:frame.getContentPane().add (panel)
设置 JPanel 的边界: panel.setBounds(...)
将 JLabel 添加到 JPanel: panel.add(label)
Just a quick question here. I have a program in which I need to create a number of JPanels, which will then each contain some objects (usually JLabels).
There are a few operations that I have to do each time i create a new JPanel, and I'm wondering if the order in which I do them has any bearing, or if there is a standard practice.
The operations I do are the following:
Declare the JPanel: JPanel panel = new JPanel(...)
Declare the JLabel: JLabel laberl = new JLabel...
Add the JPanel to some other content pane: frame.getContentPane().add(panel)
Set the bounds of the JPanel: panel.setBounds(...)
Add the JLabel to the JPanel: panel.add(label)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,只要将所有组件添加到面板中,并且在使框架可见“之前”将面板添加到内容窗格中,顺序并不重要。
标准做法是使用布局管理器,因此无需设置添加到内容窗格的面板的边界。
In general order isn't important as long as you add all the components to the panel and the panel is added to the content pane "before" you make the frame visible.
The standard practice is to use a layout manager, so there would be no need to set the bounds of the panel you added to the content pane.
顺序并不重要。但是,创建并添加所有内容后,您需要在面板上调用
revalidate()
(或在其父窗口上调用pack()
)这样布局管理器(我假设您正在使用一个!)按应有的方式排列组件。The order doesn't matter. However, after creating and
add
ing everything, you need to callrevalidate()
on the panel (orpack()
on its parent window) so that the layout manager (I presume you're using one!) arranges the components as they should be.有一个 createPanel() 方法,该方法返回添加了所有子项的面板。
然后,
构建和添加项目的顺序并不重要,只是当您添加子项时,您应该按照您希望它们在面板中出现的顺序
添加
它们。Have a method createPanel() that returns the panel with all its children added.
And then
The order of constructing and adding items isn't important, except that when you add children, you should
add
them in the order you want them in the panel.