2

I have a program that consists of four JButtons in a JFrame. I want to add images to the JButtons. The problem is that I can't seem to add them, despite trying multiple methods. When compiled, the output is input == null. The images are stored in the same folder as my .java files, so I can't figure out why they aren't showing up.

Main class:

import java.awt.GridLayout;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AutoProgram extends JFrame {

    private static String[] files    = {"workA","programmingA","leisureA","writingA"};
    private static JButton[] bIcons  = new JButton[4];
    private static Image[] bImg      = new Image[4];

    public AutoProgram() {
        super("Automation Project V.1");

        JPanel autoIcons = new JPanel();
        autoIcons.setLayout(new GridLayout(2,2));

        // Initialize the four buttons (w/ images)
        for(int i = 0; i < files.length; i++) {
            bIcons[i] = new JButton();
            try {
                bImg[i] = ImageIO.read(getClass().getResource(files[i].toLowerCase() + ".png"));
                bIcons[i].setIcon(new ImageIcon(bImg[i]));
            } catch (Exception ex) {
                System.out.println(ex);
            }
            autoIcons.add(bIcons[i]);
        }

          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));;
          mainPanel.add(autoIcons);
          add(mainPanel);

          pack();

}}

Window class:

public class Window {

    public static void main(String[] args) {

        AutoProgram frame = new AutoProgram();

        frame.setSize(315,315);
        frame.setLocationRelativeTo(null);
        frame.setFocusable(true);
        frame.setResizable(true);
        frame.setVisible(true);
    }
}

Any help would be greatly appreciated. Thanks!

SputnicK
  • 103
  • 1
  • 10

1 Answers1

2

Before going into the answer to your question, please read the following recommendations:

  1. private static JButton[] bIcons = new JButton[4]; Creating static fields could break your program, so be careful when to use them. Not really needed in this case, please read What does the 'static' keyword do in a class?

  2. JFrame is a rigid container which cannot be placed inside others, and you're not changing it's functionallity anywhere in your program, so there's no need to call extends JFrame, it's better to create a JFrame instance then. See: Extends JFrame vs. creating it inside the program for more information about this.

  3. You're correctly calling pack() but later in the code you're calling frame.setSize(315,315); which "destroys" the changes made by pack(), use one or the other, not both, I recommend you to leave pack() call.

  4. You're not placing your program in the Event Dispatch Thread (EDT), you can fix it by changing your main(...) method as follows:

    public static void main (String args[]) {
        //Java 7 and below
        SwingUtilities.invokeLater(new Runnable() {
            //Your code here
        });
    
        //Java 8 and higher
        SwingUtilities.invokeLater(() -> {
            //Your code here
        });
    }
    

Now, let's go to the solution:

Your code works fine, I think that your errors might come from the following posibilities:

  • Calling files[i].toLowerCase() (.toLowerCase() method might be breaking your program, Java is case sensitive).
  • Your images are not PNG but JPG or JPEG (look at the extension carefully)
  • Your images are damaged
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • Thanks for the suggestions / information! I still can't seem to display my images, despite the fact that I've inspected them closely and the name and extensions match up. I've also removed `.toLowerCase` but that didn't fix it either. The images aren't damaged as I've tried using other images for the buttons and they also didn't work. It seems that my method simply isn't working period. :/ – SputnicK Jun 08 '17 at 19:06
  • Check carefully for the capital letter names, double dots, etc... It works as I ran it with some images of my own, check the images are in the same package as you said, those are my best bets – Frakcool Jun 08 '17 at 19:09
  • Did my answer actually solved your question? You got it working? @SputnicK – Frakcool Jun 08 '17 at 19:12
  • Yes! For some reason the images were inside the folder but were not being recognized in Eclipse. I fixed it by dragging the images manually into the project's package icon in Eclipse. That allowed Eclipse to recognize them as resources for the project. I don't know why Eclipse didn't automatically recognize them, but dragging them manually seemed to fix it. Thank you so much for the support :) – SputnicK Jun 08 '17 at 19:23
  • 1
    You can also right click on the project -> refresh, that could work too – Frakcool Jun 08 '17 at 19:24