Java 未在JPanel中绘制图像
这是我试图用来在屏幕上绘制图像的代码(图像的位置是正确的),代码运行,但没有在屏幕上绘制任何内容。我的程序的getFile()和paintComponent()方法:Java 未在JPanel中绘制图像,java,paintcomponent,Java,Paintcomponent,这是我试图用来在屏幕上绘制图像的代码(图像的位置是正确的),代码运行,但没有在屏幕上绘制任何内容。我的程序的getFile()和paintComponent()方法: 您确实意识到,您从未创建DrawImage的实例,也没有将其添加到任何可以显示它的内容中 public class DrawImage extends JPanel { BufferedImage image; public DrawImage() throws IOException { ge
您确实意识到,您从未创建
DrawImage
的实例,也没有将其添加到任何可以显示它的内容中
public class DrawImage extends JPanel
{
BufferedImage image;
public DrawImage() throws IOException {
getFile();
}
public void getFile() throws IOException
{
image = ImageIO.read(new File("grass.png"));
}
//...
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
在执行
frame.add(pane)
调用pane.getFile()
之前,您应该执行DrawImage pane=new DrawImage()
,而不是JPanel pane=new JPanel()
既然您总是需要在绘制DrawImage之前调用getFile(),为什么不将其放入DrawImage类的构造函数中?首先,您没有使用绘制图像的类(DrawImage) 在这一行中,JPanel pane=newjpanel();因此,必须将其更改为DrawImage pane=new DrawImage(); 第二个问题是,您没有调用getFile()方法来初始化图像对象,所以请使用下面提到的方法,或者将此方法作为您的write-in类drawImage构造函数调用
public class DrawImage extends JPanel{
BufferedImage image;
public Image getFile()
{
try {
image = ImageIO.read(new File("grass.png"));
return image;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println(image);
g.drawImage(getFile(), 0, 100, null);
}
public static void main(String[] args)
{
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
还需要调用
getFile
@peeskillet始终有一些东西:P1)g.drawImage(image,0,0,null)
应该是g.drawImage(image,0,0,this)代码>因为JPanel是图像观察者
。2) 但是在JLabel
中显示图像,并且自定义面板是多余的。3) 如果使用JLabel
,则更改frame.setSize(400400)代码>到frame.pack()代码>用于在所有平台上可靠调整大小。4) 到部署时,该映像可能会成为一个新的应用程序。在这种情况下,必须通过URL
而不是File
访问资源。有关形成URL
的方法,请参见标签的。切勿使用paintComponent
方法创建图像。每次面板调用paintComponent
时,都会反复创建图像,这可能是由于多种原因造成的。
public class DrawImage extends JPanel{
BufferedImage image;
public Image getFile()
{
try {
image = ImageIO.read(new File("grass.png"));
return image;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println(image);
g.drawImage(getFile(), 0, 100, null);
}
public static void main(String[] args)
{
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}