ImageIcon显示为一个小方块

时间:2015-06-01 09:58:23

标签: java swing imageicon

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

default.png = a busy cat *********

我看到的内容 = a busy cat *********

我不认为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);

}


}

2 个答案:

答案 0 :(得分:1)

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

enter image description here

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

答案 1 :(得分:0)

我通过添加Panel类构造函数来解决这个问题:

setPreferredSize(new Dimension( 500, 500 ));