JPanel zero-width height at startup

Why jPanel returns 0 for height and width at startup and how can I get the correct values ​​at startup.

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
source share
1 answer

The panel returns 0, 0 because it is just the default value.

When you add a panel to the frame and call pack() in the frame, it will calculate the correct (preferred) size and set it. Until then, you cannot find the size because it has not been calculated.

Why do you need these values? If you can explain the problem in a broader sense, we can help you.

+3
source

All Articles