I can not put image in a JButton [closed]

-2

I tried to put the image but only gives NullPointerException , I already tried to create a folder called img inside the folder src and point there but without success too. I do not know what I might be doing wrong. The image is in the directory.

Follow the code:

public class GuiTeste {
JFrame frame = new JFrame();
JButton bTOrdenar = new JButton();

public void iniciar() {
bTOrdenar.setIcon(new javax.swing.ImageIcon(getClass().getResource("img/iconOrganize.png")));
frame.setSize(520,120);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(BorderLayout.NORTH,bTOrdenar);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
    GuiTeste teste= new GuiTeste();
    teste.iniciar();
}

}

I also tried the command:

Image img = ImageIO.read(getClass().getResource("img/IconLoad2.bmp")); bTOrdenar.setIcon(new ImageIcon(img));

    
asked by anonymous 30.10.2018 / 14:08

1 answer

1

Your code is not playable, but to work, the image must be in the img package at the same level of the class within your project in the IDE. If a img package does not exist, the image will not be found and nullpointer will pop up. Check in your project if the package exists and is at the same level as the class that is trying to access it.

To exemplify the hierarchy in a project without a package naming (not recommended):

Beingthisway,classandpackageimgwithinthesamepackage,thecodeexecuteswithouterrors.

Asmentionedinthecommentsandasyoucanseeinthefigure,youareusingapackagehierarchyofyourownineclipse,andtheidealistoalwaysinformthecompletepath,inyourcase,itwouldbe:

getClass().getResource("/br/com/williamcasa/servicodeordenacao/icons/iconOrganize.png");
    
30.10.2018 / 14:33