如何将图片添加到JButton?

50

我正在尝试为JButton添加一张图片,但不确定缺少了什么。当我运行以下代码时,该按钮的外观与没有添加任何图像属性的情况下创建的按钮完全相同。Water.bmp位于我的项目文件夹的根目录中。

ImageIcon water = new ImageIcon("water.bmp");
    JButton button = new JButton(water);
    frame.add(button);

那应该可以运行...你能否尝试使用ImageIcon构造函数的URL形式并查看它的效果?可能是因为某些原因无法找到图像文件。 - Cameron Skinner
是的,现在它正在运作。代码没有做任何更改。感谢大家的建议。 - kevinstueber
11个回答

0

eclipse示例:
阅读以上内容后,我仍需要进行更多的研究才能理解在eclipse中如何存储图像资源以及放置的位置。
结果是:在eclipse中,您需要将图像存储在任何“源文件夹”(例如“src”)下方或在“文件夹”下方。
您可以通过右键单击项目,“新建”->“源文件夹”或“新建”->“文件夹”来创建它们。任何文件夹名称都可以。"<Source Folder>/<image Folder>"的示例为"src/images"或"resource/img"。
以下是一些完全运行的示例代码,其中期望在“images”文件夹中有两个按钮图像,“Button-Image-Up.png”和“Button-Image-Down.png”:

import javax.swing.JDialog;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class ImageButtonDlg extends JDialog {
    // define button images and fall-back text
    private static gstrTxt="<Button Fall-back Text>"; // in case image does not load
    private static String gstrImgUp="Button-Image-Up.png";   // regular image
    private static String gstrImgDown="Button-Image-Down.png"; // button pressed image
    private static String gstrImgFolder="images";   // image folder, "/images" is also fine
    public static void main(String[] args) {
        ImageButtonDlg dialog = new ImageButtonDlg();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }
    /**
     * Create the dialog.
     */
    public ImageButtonDlg() {
        initializeDialog();
    }
    /**
     * Create a new ImageIcon from an image resource. 
     * The input can be: 
     * - an image file name, e.g. <image.png> 
     * - a relative path, e.g. <image/image.png>
     * - an absolute path, e.g. </home/user/dev/image.png>
     * In eclipse, images can be stored below any project "Source folder", 
     * such as "src".
     * ├── src
     * │   ├── img1.png
     * │   └── images
     * │       └── img2.png
     * ├── resources
     * │   ├── img3.png
     * │   └── images
     * │       └── img4.png
     * └── img5.png
     *  In above example img1.png to img4.png are found by 
     *  image file name or relative path
     *  However, img5 is stored in the project root folder and 
     *  needs an absolute path.
     *    
     * @param strImagePath - image filename, absolute path or relative path
     * @return new ImageIcon or 'null' if load fails
     */    
    public static ImageIcon getResourceImageIcon(String strFilepath) {
        ClassLoader loader = null;
        URL url = null;
        Image img=null;
        ImageIcon imgIcon=null;
        loader = ImageButtonDlg.class.getClassLoader();
        System.out.println(loader.toString());
        try {  // file location: <a relative path>
            url = loader.getResource("images/"+strFilepath);
            if(url==null) {
                System.out.printf("ImageButtonDlg.class.getResource(%s)=>null\n", "images/"+strFilepath);
            }
        } catch (Exception e0) {
            e0.printStackTrace();
        }
        if(url==null) {
            try {  // file location: <image filename>
                url = loader.getResource(strFilepath);
                if(url==null) { 
                    System.out.printf("Util.class.getResource(%s)=>null\n", strFilepath);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        try {
            img = ImageIO.read(url);
        } catch (Exception e2) {
            e2.printStackTrace();
            System.exit(0);
        }
        if (img!=null){
            imgIcon = new ImageIcon(img);
        }
        return imgIcon;
    }
    /**
     * Create JButton with Image
     * In case Image load fails, we create a JButton with text
     * @param strImgPath - path to Image
     * @param strAltText - fall-back text
     * @return
     */
    public static JButton getNewJButtonWithImageIcon(String strImgPath, String strAltText) {
        JButton btnReturn = null;
        ImageIcon imgIcon = getResourceImageIcon(strImgPath);
        if (imgIcon!=null){
            btnReturn = new JButton(imgIcon);
        }
        else {
            btnReturn = new JButton(strAltText);
        }
        return btnReturn;
    }
    /**
     * Image button was pressed, display a message box
     */
    private void actionImageButtonPressed() {
        try {
            JOptionPane.showMessageDialog(null, "Image Button was pressed", "Info", JOptionPane.INFORMATION_MESSAGE);
        }
        catch (Exception e) {
            ; // ignore
        }
    }
    /**
     * Initialize the dialog
     * add a button panel and the image button to the window/content pane
     */
    private void initializeDialog()
    {
        this.setTitle("Image Button Example");
        this.setResizable(false);
        this.setBounds(200, 200, 699, 601);
        JPanel panelButton = new JPanel();
        panelButton.setLayout(new FlowLayout(FlowLayout.RIGHT)); // all buttons in a row
        getContentPane().add(panelButton, BorderLayout.SOUTH); // button pane at the bottom of the window
        // create the Image Button
        JButton btnImageButton = getNewJButtonWithImageIcon(gstrImgUp, gstrTxt);
        btnImageButton.setToolTipText("<Explain what pressing the Button does>");
        btnImageButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                actionImageButtonPressed();// The Action
            }
        });
        // load button image when button clicked/released
        btnImageButton.addMouseListener((MouseListener) new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                btnImageButton.setIcon(getResourceImageIcon(gstrImgDown));              
            }
            public void mouseReleased(MouseEvent e) {
                btnImageButton.setIcon(getResourceImageIcon(gstrImgUp));
            }
        });
        btnImageButton.setActionCommand("ImageButtonAction");
        // add button to button panel
        panelButton.add(btnImageButton);
    }
}

玩得开心!
Volker Fröhlich
P.S.:
也许有人可以分享额外的实践经验。

  • 在Eclipse的“WindowBuilder编辑器”中,这样的图像按钮会显示出来,但无法访问 - 是否有解决方法?
  • NetBeans的方法是否有所不同?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接