Hinzufügen von Bildern auf JPanel in Eclipse

Habe ich das in meiner main-Klasse:

panel.setBackground(Color.green);
ImagePanel background = new ImagePanel("Images/background.png");
panel.add(background);

Aber wenn ich es starten ich sehe nur den grünen hintergrund und erhalten Sie die Ausnahme:

"javax.imageio.IIOException: Can ' T read input file!"

Dies ist die Klasse ImagePanel:

public class ImagePanel extends JPanel {
private BufferedImage img;

public ImagePanel(String path) {
    //load the background image
    try {
        img = ImageIO.read(new File(path));
    } catch(IOException e) {
        e.printStackTrace();
    }
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    //paint the background image and scale it to fill the entire space
    g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}

Ich verwende Eclipse und das ist, wo mein Bild ist: src/Images/hintergrund.png


Ok, jetzt habe ich:

ImagePanel background = new ImagePanel("src/Images/background.png");

und es nicht zeigen Ausnahme mehr, aber ich glaube trotzdem nicht, siehe Bild, nur der grüne hintergrund...

Hier ist die vollständige Methode:

 private void createAndShowGUI() {

        frame = new JFrame("Java 2048 By Xandru");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLayout(null);

        panel = new JPanel();
        panel.setLayout(null);
        panel.setBounds(0, 0, HEIGHT, WIDTH);
        panel.setBackground(Color.green);
        frame.add(panel);

        //Add the background
        ImagePanel background = new ImagePanel("src/Images/background.png");
        panel.add(background);

        //Create the main Frame
        frame.pack();

        //Set dimensions
        frame.setSize(WIDTH, HEIGHT);

        //Center it
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((screen.getWidth() - frame.getWidth()) /2);
        int y = (int) ((screen.getHeight() - frame.getHeight()) /2);
        frame.setLocation(x, y); 

        //Set visible
        frame.setVisible(true);
    }
  • Aus einem design-POV, public ImagePanel(String path) { sollte public ImagePanel(Image image) { (IMO). So kann die Platte behandeln Sie ein Bild aus Datei, URL oder ..im Arbeitsspeicher generiert.
InformationsquelleAutor XandruDavid | 2014-04-14
Schreibe einen Kommentar