关于使用 JPanels 的 Java 简单问题

发布于 2024-08-24 07:38:46 字数 410 浏览 3 评论 0原文

这里只是一个简单的问题。我有一个程序,需要在其中创建许多 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

女皇必胜 2024-08-31 07:38:46

一般来说,只要将所有组件添加到面板中,并且在使框架可见“之前”将面板添加到内容窗格中,顺序并不重要。

标准做法是使用布局管理器,因此无需设置添加到内容窗格的面板的边界。

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.

通知家属抬走 2024-08-31 07:38:46

顺序并不重要。但是,创建并添加所有内容后,您需要在面板上调用 revalidate() (或在其父窗口上调用 pack())这样布局管理器(我假设您正在使用一个!)按应有的方式排列组件。

The order doesn't matter. However, after creating and adding everything, you need to call revalidate() on the panel (or pack() on its parent window) so that the layout manager (I presume you're using one!) arranges the components as they should be.

清风疏影 2024-08-31 07:38:46

有一个 createPanel() 方法,该方法返回添加了所有子项的面板。

Panel p = createPanel();
p.setBounds(...); // if you must
frame.getContentPane().add(p);

然后,

Panel createPanel() {
  Panel p = new Panel();
  Label l = new Label("Heading");
  p.add(l);
  return p;
}

构建和添加项目的顺序并不重要,只是当您添加子项时,您应该按照您希望它们在面板中出现的顺序添加它们。

Have a method createPanel() that returns the panel with all its children added.

Panel p = createPanel();
p.setBounds(...); // if you must
frame.getContentPane().add(p);

And then

Panel createPanel() {
  Panel p = new Panel();
  Label l = new Label("Heading");
  p.add(l);
  return p;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文