所以我有自己的自定义 JFrame
,我试图在其中创建一个自动调整大小的图像以包含在我的 JFrame
的内容 中JPanel
, frameContent
. JPanel
的布局管理器是 MigLayout
,所以我想我会再次创建一个 JPanel
的子项,称为 ImagePanel
。这是我的 ImagePanel 类
最终的样子:
class ImagePanel extends JPanel{
private static final long serialVersionUID = -5602032021645365870L;
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File(getClass().getResource("../res/Title.png").toURI()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, getWidth(), getHeight(), null);
}
}
现在由于某种原因它似乎并没有真正“工作”。当我设置主要的 JFrame
内容时,我调用:
framecontent.add(new ImagePanel(), "pos 5% 5% 95% 45%");
并不是说它没有添加组件,因为使用这段代码我可以获得以下屏幕:
注意它如何勾勒出灰色背景下的区域,这意味着 paintComponent(g)
方法正在运行,而且程序也没有输出任何错误,这很奇怪,所以这意味着它正在寻找我的图像,而不是放置它。
这是我的文件层次结构:
Project Folder >
src >
res >
Title.png (Picture I want to retrieve)
guiwork >
Working.class (Class that is running instructions/ main)
全部搞定,这是自动调整大小的结果:
最佳答案
Notice how it outlines the area against the gray background, meaning the paintComponent(g) method is being run, and the program also isn't outputting any errors, which is strange, so that means it is finding my image, just not placing it.
不是这样,因为空图像不会抛出任何错误。要证明这一点,请在 paintComponent 方法中测试您的图像变量,您可能会发现它实际上为空。
即,试试这个:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("image is null: " + (image == null)); // TODO: Delete this
g.drawImage(image, getWidth(), getHeight(), null);
}
解决方案:不要将资源更改为文件,而是按原样使用资源,并确保在正确的位置查找它。
编辑
噢,chit,您正在将图像绘制到组件的边界之外:
g.drawImage(image, getWidth(), getHeight(), null);
尝试:
g.drawImage(image, 0, 0, null);
编辑2
如果您尝试一个简单的测试程序会怎样,例如:
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class TestImage {
public TestImage() throws IOException {
String path = "/res/Title.png";
BufferedImage img = ImageIO.read(getClass().getResource(path));
ImageIcon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
}
public static void main(String[] args) {
try {
new TestImage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
并确保将其放置在与当前类(class)相同的位置。它运行了吗?
关于Java Swing 在 MigLayout 中添加图像代码似乎不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737974/