Insert background image in JPanel [duplicate]

2

I already checked and the path is correct, but when I run nothing appears on the screen:

public class MapaInterface extends JPanel implements ActionListener {

private Image fundo;
public static Agente daenerys;
private Timer timer;

public MapaInterface() {
    String caminho = "/res/mapaGot.png";
    URL url = getClass().getResource(caminho);
    ImageIcon referencia = new ImageIcon(caminho);
    fundo = referencia.getImage();
    timer = new Timer(5, this);
    timer.start();
}

public void Paint(Graphics g) {
    Graphics2D graficos = (Graphics2D) g;
    //null = fundo estático
    graficos.drawImage(fundo, 0, 0, null);
    //atualiza a imagem
    graficos.drawImage(daenerys.getImagem(), daenerys.getPosicao().getX(), daenerys.getPosicao().getY(), this);
    g.dispose();
}

@Override
public void actionPerformed(ActionEvent e) {
    repaint();
}

public static Agente getDaenerys() {
    return daenerys;
}

public static void setDaenerys(Agente daenerys) {
    MapaInterface.daenerys = daenerys;
}

When I call the class:

public class ContainerDeJanelas extends JFrame{

    public ContainerDeJanelas(){
        add(new MapaInterface());
        setTitle("Heurística Game of Thrones");
        //tamanho da tela
        setSize(750,750);
        //usuario nao pode redimensionar a tela
        setResizable(false);
        //evento ao clicar em fechar
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //onde a janela vai aparecer (null = centro)
        setLocationRelativeTo(null);

        setVisible(true);
    }
}

main:

   ContainerDeJanelas containerDeJanelas = new ContainerDeJanelas();
    
asked by anonymous 23.07.2016 / 16:02

1 answer

0

I found a solution that consists of finding the absolute path of the image from the path from which the program is running; and add the relative path of the image to it.

By adapting to your program, change the constructor of the MapInterface class to:

public MapaInterface() {
    String caminhoRelativo = "/res/mapaGot.png";

    String caminhoExecucao = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

    String caminhoAbsoluto = caminhoExecucao + caminhoRelativo ;

    ImageIcon referencia = new ImageIcon(caminhoAbsoluto );
    fundo = referencia.getImage();    
    timer = new Timer(5, this);
    timer.start();
}
    
28.07.2016 / 16:47