How to load a background image in a Java Canvas

0

Hello!

I need to upload the next image in a Canvas that I'm using

This is the code which is loading the canvas

public JFrameJuegoBase() {
        initComponents();
        canvas = new CanvasDibujable();
       canvas.setBounds(30,30,720,600);
       canvas.setBackground(Color.WHITE);    
        this.add(canvas);       
        cliente=new Cliente();      
    }

Currently I have the panel when I deploy the project

Basically what I need is to place that grass background in the JPanel of my application using the Canvas

I add CanvasDibujable.java class

public class CanvasDibujable extends JPanel implements Runnable{

    private ControladorTank controladorBola;

    public CanvasDibujable(){
        super();
        controladorBola=new ControladorTank();
    }

    @Override
    public void run() {
        while(true){
            this.repaint();
        }
    }



    @Override
    public void paint(Graphics graphics){
        super.paint(graphics);
        getControladorBola().dibujarBola(graphics,
                getControladorBola().getBola());
        getControladorBola().dibujarBola(graphics,
                getControladorBola().getBola2());
    }

    /**
     * @return the controladorBola
     */
    public ControladorTank getControladorBola() {
        return controladorBola;
    }

    /**
     * @param controladorBola the controladorBola to set
     */
    public void setControladorBola(ControladorTank controladorBola) {
        this.controladorBola = controladorBola;
    }


}
    
asked by Sebastian Salazar 11.04.2018 в 02:23
source

1 answer

1

Greetings, Sebastian.

To draw an image in JPanel overwrites the paintComponent method and uses the drawImage method like this:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(fondo, 0, 0, getWidth(), getHeight(), null);
}

Where fondo is the image you want to draw. This image must be defined in your class CanvasDibujante and loaded in the constructor of that class:

private ControladorTank controladorBola;
private BufferedImage fondo;

public CanvasDibujable(){
    super();
    controladorBola=new ControladorTank();

    try {
        this.fondo = ImageIO.read(new File("C:\fondo.jpg"));
    } catch (IOException e) {
        // Controlar la excepcion si la imagen no se encuentra o no se pudo cargar
    }
}

// Aquí hay más código...

The result is the following:

Here you have the Java documentation for the Graphics method where you can find more information about drawImage methods.

And besides, you can upload the background image in different ways, I preferred to use the class ImageIO this is at your disposal. ; -).

    
answered by 12.04.2018 / 20:26
source