如何将图像添加到 JButton

发布于 2024-10-14 11:05:50 字数 239 浏览 8 评论 0原文

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

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

I am trying to add an image to a JButton and I'm not sure what I'm missing. When I run the following code the button looks exactly the same as if I had created it without any image attribute. Water.bmp is in the root of my project folder.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

定格我的天空 2024-10-21 11:05:50

我认为你的问题在于图像的位置。您应该将其放置在源中,然后像这样使用它:

  JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {
    System.out.println(ex);
  }

在本例中,假设图像位于 src/resources/ 文件夹中。

I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

  JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
    button.setIcon(new ImageIcon(img));
  } catch (Exception ex) {
    System.out.println(ex);
  }

In this example, it is assumed that image is in src/resources/ folder.

短暂陪伴 2024-10-21 11:05:50

@Rogach

,您可能想添加:

// to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);

@Rogach

and you may like to add:

// to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);
尴尬癌患者 2024-10-21 11:05:50

它看起来像是一个位置问题,因为该代码非常适合添加图标。

由于我不知道您的文件夹结构,我建议添加一个简单的检查:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

这样,如果您的路径名错误,它会告诉您,而不是不显示任何内容。如果文件不存在,则应抛出异常。

It looks like a location problem because that code is perfectly fine for adding the icon.

Since I don't know your folder structure, I suggest adding a simple check:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

This way if you ever get your path name wrong it will tell you instead of displaying nothing. Exception should be thrown if file would not exist, tho.

小…楫夜泊 2024-10-21 11:05:50

您将图像放入资源文件夹中并使用以下代码:

JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));

You put your image in resources folder and use follow code:

JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));
断念 2024-10-21 11:05:50
public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

或使用此代码

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }
public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }
呆° 2024-10-21 11:05:50

我只做了一件事,它对我有用..检查你的代码是否有这个方法..

setResizable(false);

如果它是假的,那就让它为真,它会工作得很好..
我希望它有帮助..

I did only one thing and it worked for me .. check your code is this method there ..

setResizable(false);

if it false make it true and it will work just fine ..
I hope it helped ..

傲世九天 2024-10-21 11:05:50
buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));
buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));
○愚か者の日 2024-10-21 11:05:50
//paste required image on C disk
JButton button = new JButton(new ImageIcon("C:water.bmp");
//paste required image on C disk
JButton button = new JButton(new ImageIcon("C:water.bmp");
撩动你心 2024-10-21 11:05:50

这段代码对我有用:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);

This code work for me:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);
等风来 2024-10-21 11:05:50

例如,如果文件夹 res/image.png 中有图像,您可以这样写:

try
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("image.png");
    // URL input = classLoader.getResource("image.png"); // <-- You can use URL class too.
    BufferedImage image = ImageIO.read(input);

    button.setIcon(new ImageIcon(image));
}
catch(IOException e)
{
    e.printStackTrace();
}

在一行中:

try
{
    button.setIcon(new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("image.png"))));
}
catch(IOException e)
{
    e.printStackTrace();
}

如果图像比按钮大,则不会显示。

For example if you have image in folder res/image.png you can write:

try
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("image.png");
    // URL input = classLoader.getResource("image.png"); // <-- You can use URL class too.
    BufferedImage image = ImageIO.read(input);

    button.setIcon(new ImageIcon(image));
}
catch(IOException e)
{
    e.printStackTrace();
}

In one line:

try
{
    button.setIcon(new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("image.png"))));
}
catch(IOException e)
{
    e.printStackTrace();
}

If the image is bigger than button then it will not shown.

月亮是我掰弯的 2024-10-21 11:05:50

日食示例:
读完上面的内容后,我仍然需要更多的研究来了解如何使用 eclipse 放置图像资源以及如何放置图像资源。
结果:在 Eclipse 中,您需要将图像存储在任何“源文件夹”(例如“src”)下或“文件夹”下面。
您可以通过右键单击项目“新建”->“源文件夹”或“新建”->“文件夹”来创建这两个文件夹。任何文件夹名称都可以。 “<源文件夹>/<图像文件夹>”的示例是“src/images”或“resource/img”。
下面是一些功能齐全的示例代码,需要两个按钮图像,“Button-Image-Up.png”和“Button-Image-Down.png”位于文件夹“images”中:

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

玩得开心!
沃尔克·弗罗利希
PS:
也许有人可以分享更多的实践经验。

  • 在 eclipse“WindowBuilder Editor”中显示了此类图像按钮,但无法访问它们 - 有一些解决方法吗?
  • NetBeans 方法是什么(如果有不同)?

eclipse example:
After reading the above, it still took me more research to understand, where and how to place image resources, using eclipse.
The outcome: in eclipse you need to store images underneath any "Source Folder" (such as "src") or below in a "Folder".
You create both by right-clicking on your project, "New"->"Source Folder" or "New"->"Folder". Any folder name is fine. Examples for "<Source Folder>/<image Folder>" are "src/images" or "resource/img".
Here's some fully functioning sample code, which expects two button images, "Button-Image-Up.png" and "Button-Image-Down.png" in folder "images":

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

Have Fun!
Volker Fröhlich
P.S.:
Perhaps someone can share additional practical experience.

  • In eclipse "WindowBuilder Editor" such image buttons are shown, but they cannot be accessed - is there some workaround?
  • What is the NetBeans approach, if any different?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文