我在做一個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