Skip to content

Why is my image not being added? JavaSwing

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.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() {

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


    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 ="/monkiflipppp.gif"));
        } catch (IOException e1) {

    public void paint(Graphics 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);


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




monkiFlipImage is not initialized, simply put you aren’t loading the gif. (monkiFlipImage ="/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.