Search code examples
javaimageswingjpanelpaintcomponent

drawImage() method draws the image small regardless of image size


I have an imagepanel class that draws an image on a JPanel. My problem is that the image appears to be very small inside the jpanel, and I dont know why.

I have done all I could and searched the net and even some java books for this little problem but to no success. I really need some help on this one.

I am extremely new to java.

    class Weapons extends JPanel {
    private Image weaponimage = weapon1.getImage();

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (image != null)
        g.drawImage(weaponimage, 0, 0, getWidth(), getHeight(), this);
   }
   }

that's the image class.


Solution

  • The 'instant fix' is to paint that element at its natural size. E.G. Change this:

    g.drawImage(weaponimage, 0, 0, getWidth(), getHeight(), this);
    

    To this:

    g.drawImage(weaponimage, 0, 0, this);
    

    Which seems logical. A 'weapon' should probably be drawn at natural size.


    ..problem is that the image appears to be very small inside the jpanel,

    No. The problem seems to be that the panel itself is very small. The image is painted the width and height of the panel as assigned by the layout.

    To increase the size of the (BG) image, add components to the panel (properly laid out) and display the panel at its preferred size.