如何在JPanel上绘制PNG图像?

时间:2014-03-05 20:15:43

标签: java image swing drawing jpanel

我正在尝试通过覆盖paintComponent方法将图像绘制到JPanel上。但是,我根本没有运气,我不知道为什么。

这是我目前获得的代码:

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);
    }
}

主要

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


    }
}

1 个答案:

答案 0 :(得分:3)

这可能不起作用的原因很多

  • 图片可能未加载。您应该使用ImageIO.read,因为如果出现问题,它会抛出IOException
  • 布局管理器使用面板的首选大小,默认为0x0,使组件实际上不可见
  • 您没有将窗口设置为可见...

例如

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

然后在你的Window类......

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);
}

更简单的孤独就是使用JLabel ...

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

请查看How to use LabelsReading/Loading an Image了解详情