Why is my image not being added? JavaSwing

Tags: ,



I made this program, assume I have an extra src folder in my buildpath with the monkiflipppp.gif there. It just runs and has a button, but the button won’t actually do anything… Not sure if I need to add a specific method to the constructor. Essentially I just want the monkiflippp gif to post in different locations every time I click the button.

package heFlip;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JPanel;

public class addMonki extends JPanel {

    public addMonki() {
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                x = random.nextInt(getBounds().width - 100);
                y = random.nextInt(getBounds().height - 100) + 100;
                repaint();
            }

        });
        add(button);
    }

    public BufferedImage monkiFlipImage;
    JButton button = new JButton("Add Monki");
    Random random = new Random();
    private static final long serialVersionUID = -6936208004287181389L;

    int x = 0, y = 0;

    public void addsMonki() {
        try {
            monkiFlipImage = ImageIO.read(getClass().getResource("/monkiflipppp.gif"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawImage(monkiFlipImage, x, y, this);
    }

}

Here’s my driver in case you’re curious.

package heFlip;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Driver {

    private static final long serialVersionUID = 1L;

    public static void createAndShowGUI() {
        JFrame frame = new JFrame("monki flip");
        frame.add(new addMonki());
        frame.setSize(1366, 768);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

Answer

monkiFlipImage is not initialized, simply put you aren’t loading the gif. (monkiFlipImage = ImageIO.read(getClass().getResource("/monkiflipppp.gif"));) You forgot to use addsMonki at all.

I tested your code by adding addsMonki at the first line of the constructor (public addMonki() {) and it works just fine.



Source: stackoverflow