为什么jPanel在启动时返回高度和宽度为0,如何在启动时获得正确的值。
import javax.swing.JPanel;
class ZeroJPanel extends JPanel {
/**
* Creates new form ZeroJPanel
*/
ZeroJPanel() {
initComponents();
System.out.println( this.getHeight() );
}
public static void main(String Args[]) {
new ZeroJPanel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
答案 0 :(得分:3)
面板返回0, 0
,因为很简单,这是默认值。
将面板添加到框架并在框架上调用pack()
时,将计算正确(首选)尺寸并进行设置。在此之前,您将无法找到尺寸,因为它尚未计算。
为什么需要这些值?如果您能从更广泛的角度解释问题,我们可以帮助您。