Search code examples
javapolygons

How can I get a JPanel's width and height from within the constructor?


So I have a class that draws stuff to a JPanel, but to do this I need to instantiate polygons in the constructor. But I am a bit perplexed at this bit; I create the JFrame and add the JPanel extending class "Field" to it like so,

public class mainSetup {
    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setSize(600,600);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(new Field());
        frame.pack();
    }

}

and this is the JPanel's code:

public class Field extends JPanel implements ActionListener{
    public Field(){

        System.out.println(getWidth());
    }
    @Override
    public void paintComponent(Graphics g){
        System.out.println(getWidth());
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        repaint();

    }


}

Why does the getWidth() call in the constructor print a 0 while the getWidth() call in the paintComponent method returns 594? In fact - why aren't either of these numbers the 600 I was expecting? Why do they vary?


Solution

  • A swing component doesn't yet have a width when it is constructed. It first has to be added to a container, after which the layout manager will assign a location and dimensions to the component.

    As to why it isn't 600 but 594 - each swing component has "insets" that are occupied by the border. They have a default width depending on your PLAF. In this case the insets on the left and the right of the content pane of the JFrame are likely 3 and 3 pixels, adding up to 6, and 600 - 6 = 594.