.pack() 有什么作用?

编程入门 行业动态 更新时间:2024-10-26 21:26:28
本文介绍了.pack() 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习 JPanel 和 GridLayout ,这段代码将生成一个带有 6 个按钮的简单 JPanel

I am learning about JPanel and GridLayout , this snippet of code will produce a simple JPanel with 6 buttons

package testing; import java.io.*; import java.util.*; import java.security.*; import javax.xml.bind.DatatypeConverter; import java.lang.*; import java.awt.*; import javax.swing.*; public class Testing { public static class GridPanel extends JPanel { public GridPanel() { setLayout(new GridLayout(2,3)); setBackground(Color.GREEN); this.setPreferredSize(new Dimension(500,500)); JButton b1 = new JButton ("Button 1"); JButton b2 = new JButton ("Button 2"); JButton b3 = new JButton ("Button 3"); JButton b4 = new JButton ("Button 4"); JButton b5 = new JButton ("Button 5"); JButton b6 = new JButton ("Button 6"); add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); } } public static void main(String[] args) { GridPanel gp = new GridPanel(); JFrame jf = new JFrame(); jf.add(gp); jf.pack(); //code wouldnt work if i comment out this line jf.setVisible(true); } }

我想知道如果我注释掉 jf.pack()

I am wondering why my code wouldnt work if i comment out jf.pack()

推荐答案

pack 方法调整框架的大小,使其所有内容都等于或大于其首选大小.pack 的另一种方法是通过调用 setSize 或 setBounds(也设置帧位置)来显式建立帧大小.一般来说,使用 pack 比调用 setSize 更可取,因为 pack 让框架布局管理器负责框架大小,而布局管理器擅长调整平台依赖性和其他影响组件大小的因素.

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

来自 Java 教程

您还应该参考 Javadocs 任何时候您需要有关任何 Java API 的附加信息

You should also refer to Javadocs any time you need additional information on any Java API

更多推荐

.pack() 有什么作用?

本文发布于:2023-10-07 17:20:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么   作用   pack

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!