Create java icon button?

Asked

Viewed 911 times

1

I’m having trouble creating an icon button in java, I’ve looked at several tutorials, but I can’t make it work.

Note: I am using eclipse, Windows 10. The folder that is the image is src where the Main class file is.

    import javax.swing.*;
    import java.awt.*;

    public class Main {
       public static void main(String[] args) {
            JFrame frame = new JFrame();

            Icon imageIcon = new ImageIcon("flag.png");
            frame.add(new JButton("Flag",imageIcon));

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300,400);
            frame.setVisible(true);

       }
   }
  • Something like that? https://answall.com/q/15490/3117

1 answer

0


Usually, it works by having the image in the same folder as the compiled file (.class). I tested your code with any image and worked perfectly (compiling "in hand"). But, doing so, the image will not be part of the .jar Generated, only serves for tests.

The recommended is to put your images in the folder Resources/Images and modify the code for something like:

Icon imageIcon = new ImageIcon(Main.class.getResource("/Images/flag.png"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.