在Java中,默认的JPanel高度和宽度是多少?
In Java, what is the default JPanel height and width?
我创建了 class,如下所示。当我创建一个名为此 class 的 drawpanel 对象并使用 frame.getContentPane().add(BorderLayout.CENTER, drawpanel) 添加到框架时,我得到了一个预期的黑色背景矩形。这是否意味着面板的 this.getWidth 和 this.getHeight 默认情况下具有与框架相同的高度和宽度(这就是为什么它用黑色填充整个框架的原因)?
我想重新构建问题的另一种方式是 - 如果我通过扩展 JPanel 创建自定义小部件,并且在实例化此自定义小部件时,它的默认高度和宽度是多少?
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g){
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
我认为 JPanel 本身的首选大小为 0,0。但是如果你给它添加一些具有更高首选尺寸的组件,它的首选尺寸就不会是0。
Does it mean that the Panel's this.getWidth and this.getHeight by default has the same the height and width of the Frame (which is why it fills up the entire frame with black colour) ?
不,这意味着框架有一个 layout/constraint (BorderLayout
/CENTER
),它会将组件拉伸到可以填充它的任何大小。
If I create a custom widget by extending JPanel, and when this custom widget is instantiated, what is its default height and width ?
0x0(未布置任何组件)。
完成自定义绘画的面板应该return内容的首选大小。一旦添加到框架中,调用 pack()
方法,它将是为了满足组件的首选大小而需要的确切大小。
JPanel
的默认大小为 0 宽和 0 高。
您可以设置尺寸:
- 手动:
panel.setSize()
、panel.setPreferredSize()
- 自动:
panel.pack()
我创建了 class,如下所示。当我创建一个名为此 class 的 drawpanel 对象并使用 frame.getContentPane().add(BorderLayout.CENTER, drawpanel) 添加到框架时,我得到了一个预期的黑色背景矩形。这是否意味着面板的 this.getWidth 和 this.getHeight 默认情况下具有与框架相同的高度和宽度(这就是为什么它用黑色填充整个框架的原因)?
我想重新构建问题的另一种方式是 - 如果我通过扩展 JPanel 创建自定义小部件,并且在实例化此自定义小部件时,它的默认高度和宽度是多少?
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g){
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
我认为 JPanel 本身的首选大小为 0,0。但是如果你给它添加一些具有更高首选尺寸的组件,它的首选尺寸就不会是0。
Does it mean that the Panel's this.getWidth and this.getHeight by default has the same the height and width of the Frame (which is why it fills up the entire frame with black colour) ?
不,这意味着框架有一个 layout/constraint (BorderLayout
/CENTER
),它会将组件拉伸到可以填充它的任何大小。
If I create a custom widget by extending JPanel, and when this custom widget is instantiated, what is its default height and width ?
0x0(未布置任何组件)。
完成自定义绘画的面板应该return内容的首选大小。一旦添加到框架中,调用 pack()
方法,它将是为了满足组件的首选大小而需要的确切大小。
JPanel
的默认大小为 0 宽和 0 高。
您可以设置尺寸:
- 手动:
panel.setSize()
、panel.setPreferredSize()
- 自动:
panel.pack()