Create button with java icon?

1

I'm having trouble creating a button with an icon in java, I've looked at several tutorials, but I can not get it to work.

Note: I am using eclipse, Windows 10. The folder that is in 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);

       }
   }
    
asked by anonymous 18.05.2017 / 21:17

1 answer

0

Typically, 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 by doing this, the image will not be part of the .jar generated, just for testing purposes.

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

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