4

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
}
4

1 に答える 1

3

パネルが戻るのは0, 0、単純に、それがデフォルト値であるためです。

パネルをフレームに追加してフレームを呼び出すとpack()、正しい (優先) サイズが計算されて設定されます。それまでは、サイズが計算されていないため、サイズを見つけることができません。

なぜこれらの値が必要なのですか? 問題をより広い意味で説明していただければ、お役に立てるかもしれません。

于 2013-03-10T02:04:21.440 に答える