我使用NetBeans,我想在jPanel上显示图像(基本上是为了让它滚动)。 我写了这个代码Java - 无法从文件中绘制图像
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
}
但是当我执行它,它显示我只是虚空的JPanel
我怎样才能使它发挥作用?
请当然,图像本身是可以访问的。请看看这个[回答](http://stackoverflow.com/a/9866659/1057230),了解如何将图像添加到Java项目中。希望它有助于:-)另外,如果您重写任何'JComponent'的'paintComponent'方法,请不要自己创建'Graphics'对象,而应使用'Swing'本身提供的对象。请确保你重写'getCompatibleSize()''JComponent'的paintComponent'被覆盖,因为一些Layout Manager倾向于给出0和0的大小,而不是:( –