为什么我的图像没有添加到我的 JButton 中?

Why aren't my images being added to my JButtons?

我有一个程序,它由一个 JFrame 中的四个 JButton 组成。我想将图像添加到 JButtons。问题是我似乎无法添加它们,尽管尝试了多种方法。编译时,输出为 input == null。这些图像与我的 .java 文件存储在同一文件夹中,所以我不明白为什么它们没有显示出来。

主要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);
    }
}

如有任何帮助,我们将不胜感激。谢谢!

在回答您的问题之前,请阅读以下建议:

  1. private static JButton[] bIcons = new JButton[4]; 创建 static 字段可能会破坏您的程序,因此在使用它们时要小心。在这种情况下并不是真的需要,请阅读 What does the 'static' keyword do in a class?

  2. JFrame 是一个刚性容器,不能放在其他容器中,并且您不会在程序的任何地方更改它的功能,因此无需调用 extends JFrame ,那么最好创建一个 JFrame 实例。请参阅:Extends JFrame vs. creating it inside the program 了解更多相关信息。

  3. 您调用 pack() 是正确的,但稍后在您调用 frame.setSize(315,315); 的代码中 "destroys" pack() 所做的更改,使用一个或另一个,而不是两个,我建议你留下 pack() 电话。

  4. 您没有将程序放在 Event Dispatch Thread (EDT) 中,您可以通过如下更改 main(...) 方法来修复它:

    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
        });
    }
    

现在,让我们来看看解决方案:

您的代码运行良好,我认为您的错误可能来自以下几种可能:

  • 调用 files[i].toLowerCase().toLowerCase() 方法可能会破坏您的程序,Java 区分大小写)。
  • 您的图片不是 PNG 而是 JPG 或 JPEG(仔细查看扩展名)
  • 您的图片已损坏