0

Hi! I'm just new at GUI programming and I've been busy creating a GUI for my project.

My image won't show up in this particular code. I've made two other classes and the images load perfectly.

import javax.swing.*;
import java.awt.image.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Battle implements ActionListener{

    JFrame frame = new JFrame("Test");
    JPanel buttons, pic;
    JButton attack, attack1,attack2,attack3,attack4;
    JLabel label;
    JLabel grid[][];
public  Battle(){

        frame.setBounds(50, 50, 500, 500);
        pic = new JPanel();
        buttons = new JPanel();


        buttons.setLayout(new GridLayout(2,2));
        attack = new JButton("Attack");
        buttons.add(attack1 = new JButton("Attack1"));
        buttons.add(attack2 = new JButton("Attack2"));
        buttons.add(attack3 = new JButton("Attack3"));
        buttons.add(attack4 = new JButton("Attack4"));
        attack.setSize(30,40);
        frame.add(attack,BorderLayout.SOUTH);

        pic.setLayout(new GridLayout(2,2));
        frame.add(pic,BorderLayout.CENTER);
        grid = new JLabel[2][2];
        pic.add(grid[0][0]= new JLabel(new ImageIcon("agumon3.png")));


        attack.addActionListener(this);
        attack1.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String args[]){
        new Battle();
    }
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==attack){
            frame.remove(attack);
            frame.repaint();
            frame.add(buttons,BorderLayout.SOUTH);

        }
        else if(e.getSource()==attack1)
        {
            JOptionPane.showMessageDialog(null, "Meow attacks arf!");
            frame.remove(buttons);
            frame.repaint();
            frame.add(attack,BorderLayout.SOUTH);

        }
    }
}
2
Contributors
1
Reply
9
Views
2 Years
Discussion Span
Last Post by JamesCherrill
1

new ImageIcon(...) is famous for not throwing any exceptions when it fails to find the file; it's just null. JLabel is happy to accept null for its image icon, so the final result is no image and no error messages. We see that quite often in DaniWeb "help!" posts.
Use the exists() method of the File class with the path/name of the file to confirm that your program can find the file. Alternatively, check the width/height of the image to confirm they are >0

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.