我使用 NetBeans,我想在 jPanel 上显示图像(基本上是为了使其滚动)。 我写了这段代码
Graphics g=jPanelScrolling.getGraphics();
File fileBackground = new File("background.jpg");
Image background;
try{
background=ImageIO.read(fileBackground);
final int WIDTH=background.getWidth(rootPane);
final int HEIGHT=background.getHeight(rootPane);
g.drawImage(background, WIDTH, HEIGHT, rootPane);
}
catch(IOException e){
background=null;
jPanelScrolling.setBackground(Color.red); //to test if the image has been succesfully uploaded
}
但是当我执行它时,它只显示 void jPanel
我怎样才能让它发挥作用?
最佳答案
尝试,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
关于Java - 无法从文件中绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970879/