简体   繁体   中英

How to draw PNG Image onto JPanel?

I'm trying to draw a image onto a JPanel by overriding the paintComponent method. However, I'm having no luck with it at all and I don't know why.

Here's the code I've got at the moment:

DrawPanel

public class DrawPanel extends JPanel{

    private Image backgroundImg;

    public DrawPanel()
    {
        backgroundImg = Toolkit.getDefaultToolkit().createImage("C:\\Users\\Administrator\\workspace\\Scrub\\src\\loginBackground.png");
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(backgroundImg, 0, 0, null);
    }
}

LoginWindow Class

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LoginWindow extends Window{

    private DrawPanel panel;

    public LoginWindow(int width, int height)
    {
        super("", width, height);


        panel = new DrawPanel();
        this.add(panel);

        panel.setVisible(true);
    }
}

Main

public class Main
{
    public static void main(String[] args)
    {
        LoginWindow loginWindow = new LoginWindow(500, 300);


    }
}

There are lots of reasons this might not work

  • The image might not be getting loaded. You should use ImageIO.read instead, as it will throw an IOException if something goes wrong
  • The layout manager is using the preferred size of your panel, which is defaulted to 0x0, making the component effectively invisible
  • You're not setting the window to be visible...

For example

public class DrawPanel extends JPanel{
    //...
    public Dimension getPreferredSize() {
        return backgroundImg == null ? new Dimesion(100, 100) : new Dimension(backgroundImg.getWidth(this), backgroundImg.gtHeight(this));
    }

And then in your Window class...

public LoginWindow(int width, int height)
{
    super("", width, height);


    panel = new DrawPanel();
    this.add(panel);

    // Swing components are visible by default
    //panel.setVisible(true);
    // windows aren't
    setVisible(true);
}

A simpler soliton would be to use a JLabel ...

setLayout(new BorderLayout());
BufferedImage img = ImageIO.read(new File(...));
JLabel label = new JLabel(new ImageIcon(img));
add(label);
setVisible(true);

Take a look at How to use Labels and Reading/Loading an Image for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM