gpt4 book ai didi

java - ImageIcon显示为小方 block

转载 作者:行者123 更新时间:2023-11-30 08:09:42 26 4
gpt4 key购买 nike

问题出在哪里。它无法正确显示图像。

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

}


}

最佳答案

这个答案解决了我对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);
}
}

关于java - ImageIcon显示为小方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30570527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com