JButton Image Icon不显示.png文件 [英] JButton Image Icon not displaying .png file

查看:236
本文介绍了JButton Image Icon不显示.png文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找解决方案,并阅读一些与此问题相关的类似帖子,但这些都不适合我。

I've been looking everywhere for a solution to this and read some similar posts related to this problem but none of them worked for me.

我正在尝试在JButton上显示图像b.png,当我滚动按钮时图标会发生变化。

I'm trying to display the image "b.png" on the JButton and when i roll over the button the icon changes.

package GUI_JButton;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Gui extends JFrame {

    private JButton reg;
    private JButton custom;

    public Gui() {
        super("Title goes here");
        setLayout(new FlowLayout());

        reg = new JButton("reg button"); // create reg button
        add(reg); // add reg button to JFrame

        // initialize images
        Icon b = new ImageIcon(getClass().getResource("images/imageA.png"));
        Icon x = new ImageIcon(getClass().getResource("images/imageB.png"));

        custom = new JButton("custom button", b); // create custom button
        custom.setRolloverIcon(x);
        add(custom); // add button to JFrame

        HandlerClass handler = new HandlerClass();
        reg.addActionListener(handler);
        custom.addActionListener(handler);

    }

    private class HandlerClass implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null,
                    String.format("%s", event.getActionCommand()));

        }

    }

}

图像位于名为images的文件夹中,该文件夹位于src文件夹中,旁边是 Gui.java 文件和 TESTMain.java 文件。

The images are in a folder named images which is in the src folder alongside the Gui.java file and the TESTMain.java file.

我得到的错误是来自Main的空指针异常。我试过了

The error i'm getting is a null pointer exception from Main. I have tried

Icon b = new ImageIcon("images/imageA.png"); 

此编译但不显示图像。我也尝试了

This compiles but the image is not displayed. I have also tried

custom = new JButton("custom", new ImageIcon("images/imageA.png"));

custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png"));

我知道 getClass()。getResource()因为需要使用jar编译图像而受到阻止。

I know that getClass().getResource() is prefferred as the images need to be compiled with the jar.

关于让我的图像显示的任何想法?

Any ideas on getting my images to display?

推荐答案

您的图片文件夹需要与您编译的 .class 文件位于同一文件夹中,而不是 src 与您的 .java files。

Your images folder needs to be in the same folder as your compiled .class files, instead of in src with your .java files.

这篇关于JButton Image Icon不显示.png文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆