我在做一个SwingBot,无法弄清楚如何让图像出现。它编译得很好,但不可见。我究竟做错了什么? This is my image.它位于与我的代码java文件相同的目录中名为“images”的文件夹中。无法在Java中显示图像
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.Color;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.Scanner;
public class SwingBot
{
public static void main(String[] args)
{
// contruction of new JFrame object
JFrame frame = new JFrame();
// mutators
frame.setSize(400,400);
frame.setTitle("SwingBot");
// program ends when window closes
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Robot r = new Robot();
frame.add(r);
// voila!
frame.setVisible(true);
// your Scanner-based command loop goes here
int noend = 0;
System.out.println("Enter Commands");
while(noend == 0)
{
Scanner input = new Scanner(System.in);
String command = input.next();
if(command.equals("left"))
r.moveBot(10,0);
if(command.equals("right"))
r.moveBot(-10,0);
if(command.equals("down"))
r.moveBot(0,10);
if(command.equals("up"))
r.moveBot(0,-10);
// call methods on the Robot instance like w.moveBot(10,10) in response to
// user input
}
}
public static class Robot extends JComponent
{
private Rectangle rect = new Rectangle(10,10);
private BufferedImage image;
public void ImagePanel()
{
try
{
image = ImageIO.read(new File("images/flower.png"));
}
catch (IOException ex)
{
// handle exception...
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// set the color
//g2.setColor(Color.BLUE);
g.drawImage(image, 0, 0, null);
}
public void moveBot(int x, int y)
{
// move the rectangle
rect.translate(x,y);
// redraw the window
repaint();
}
}
}
尝试使用'的getClass()。的getResource( “图像/ flower.png”)'或'的getClass()。的getResource( “/图片/ flower.png”)'和'调用超。paintComponent'在做任何自定义绘画之前使用'this'作为'drawImage'的图像观察者参数 – MadProgrammer
您在异常处理中究竟做了什么?在你不知道的情况下抛出异常,因为你在'catch'块中没有做任何事情? – Josh
@John我从另一个StackOverflow答案中复制了这个。我认为它必须包括在内。抱歉。我对这一切都很陌生。 – user3200964