Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

image - Java: JPanel background not scaling

I am trying to draw an image to a JPanel in java and I have that down, good. My problem now is I am attemping to make it scale to the full size of the window, but it is not doing so. I have tried methods, and they either make the image disappear, or there is no graphical change at all.

The code I am currently working with:

class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1L;

    private Image img;

    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}

Full class at: http://pastebin.com/CpcBt2j8

I have tried adding in code such at img = img.getScaledInstance(440, 440, Image.SCALE_SMOOTH) and that has no effect whatsoever. I have also tried making a new image called scaledImg and setting img's getScaledInstance value to that, and that completely removes the image from display.

How can I get the image to be scaled to the full size I want?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To dynamically scale an image you use:

//g.drawImage(img, 0, 0, null);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

See Background Panel for a complete implementation along with a tiling feature.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...