Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 470
FartVader Avatar asked Dec 07 '25 20:12

FartVader


2 Answers

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.

like image 95
Andrew Thompson Avatar answered Dec 09 '25 08:12

Andrew Thompson


May be your class look like this:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

    class Weapons extends JPanel {
        // get image according to your application logic
        BufferedImage image;

        @Override
        public void paint(Graphics g){
            super.paintComponent(g);
            g.drawImage(image, 0, 0, getWidth() - 1, getHeight() - 1, 0, 0, image.getWidth() - 1, image.getHeight() - 1, null);
        }

        public void setImage(BufferedImage image){
            this.image = image;
        }
    }

    class Main {
        Weapons weapons;

        public void updateWeapons(){
            // create image
            BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
            // draw on image

            // TO UPDATE WEAPONS GUI, below steps are impotant
            weapons.setImage(image);
            weapons.repaint();
        }
    }

You have to override paint() method. Then you can set image and call repaint() to update graphics on panel.

like image 26
nullptr Avatar answered Dec 09 '25 09:12

nullptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!