简体   繁体   中英

Zero Width Height jPanel on start

Why does the jPanel return 0 for the height and width when it starts and how can I get the right values on start.

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
}

The panel returns 0, 0 because, quite simply, that is the default value.

When you add the panel to a frame, and call pack() on the frame, that will calculate the correct (preferred) size and set it. Until then, you won't be able to find the size because it hasn't been calculated.

Why do you need these values? If you can explain the problem in broader terms, we may be able to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM