Search code examples
javaswingjpanelpaintcomponent

Painted component bigger than frame


I am using the same numbers to set the size of my frame as I am to paint the rectangle, yet the graphics are larger than my JFrame. Why is this?

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {
    public static void main(String[] arguments) {
        Test test = new Test();
        JFrame frame = new JFrame();
        DrawPane contentPane = test.new DrawPane();
        frame.setContentPane(contentPane);
        frame.setSize(300, 400);
        frame.setVisible(true);
    }

    private class DrawPane extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(Color.YELLOW);
            g.fillRect(0, 0, 300, 400);
        }
    }
}

Solution

  • It's because of border. And it's a good example why you shouldn't explicitly determine size for your JFrame. Instead calling setSize override getPreferredSize method from your JPanel:

    private class DrawPane extends JPanel {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g); 
                g.setColor(Color.YELLOW);
                g.fillRect(0, 0, 300, 400);
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 400);
            }
        }
    

    Then call pack for your JFrame instead setSize and your JFrame will adjust it's size according to its content.