ImageIcon 显示为一个小方块

ImageIcon is displayed as a small square

哪里有问题。它没有正确显示图像。

default.png = *********

我看到了什么 = *********

我认为 png 没有问题。它也在我的 src 中,我在 eclipse 上刷新了它。

代码:

import java.awt.*;

import javax.swing.*;

public class Main {

public static void main(String[] args) {


    JFrame jf = new JFrame();

    jf.setTitle( "test");
    jf.setLayout( new FlowLayout());
    jf.setSize(350, 450);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    jf.add(new Panel());

}

}

面板:

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;


public class Panel extends JPanel {

// PROPERTIES

public ImageIcon icon;

// CONSTRUCTORS

public Panel() {

    icon = new ImageIcon(this.getClass().getResource("default.png"));
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawImage(icon.getImage(), 0, 0, null);

}


}

我通过在面板 class 构造函数中添加解决了这个问题:

setPreferredSize(new Dimension( 500, 500 ));

这个回答解决了我对 OP 回答的批评。该示例结合了各种评论中添加的建议。

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.border.LineBorder;

public class Main {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://i.imgur.com/o0E0aGD.png");
        BufferedImage bi = ImageIO.read(url);
        JFrame jf = new JFrame();

        jf.setTitle("test");
        jf.setLayout(new FlowLayout());
        //jf.setSize(350, 450); just pack()
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jf.add(new BackgroundImagePanel(bi));

        jf.pack();
        jf.setMinimumSize(jf.getSize());
        jf.setVisible(true);
    }
}

class BackgroundImagePanel extends JPanel {

    public Image img;

    // CONSTRUCTOR
    public BackgroundImagePanel(Image img) {
        this.img = img;
        this.setBorder(new LineBorder(Color.RED, 2));
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, this);
        // g.drawImage(img, 0, 0, getWidth(), getHeight(), this);  // Better!
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        int w = d.width>img.getWidth(this) ? d.width : img.getWidth(this);
        int h = d.height>img.getHeight(this) ? d.height : img.getHeight(this);

        return new Dimension(w, h);
    }
}