Add an image in a JPanel in the same class

0

hello the following is my code, but although it does not show me error and compiles, it simply does not work, I do not know if I made an error or if I put the image wrong from the beginning, because the image I have it from the download folder .

 package source;

 import java.awt.Container;
 import java.awt.Graphics;
 import java.awt.Image;
 import java.net.URL;


 import javax.swing.ImageIcon;
 import javax.swing.JFrame;
 import javax.swing.JPanel;

 public class imagen extends JFrame {

public Image imagenfondo;
public URL fondo;   

public imagen(){
    this.setBounds(0,0,400,400);
    this.setTitle("ventana");
    this.setVisible(true);
    this.setLocationRelativeTo(null);

    fondo = this.getClass().getResource("/source/puzle106.jpg");
    imagenfondo = new ImageIcon(fondo).getImage();

    Container contenedor = getContentPane();

    contenedor.add(panel);



}
public JPanel panel= new JPanel(){

public void paintComponent(Graphics g){
g.drawImage(imagenfondo, 0,0, getWidth(), getHeight(), this);

}
};

public static void main(String [] args){

//  Principal ventana  = new Principl();
}
}
    
asked by Luis Sanches Larios 09.08.2017 в 00:14
source

1 answer

1

You have several errors, to start if you are executing the code in the same way that you have it, obviously it will compile but it will not show anything because in the main you have not told it to show anything, so you should less instantiate your class Image in the main so that all the parameters that you placed in the constructor are made.

  

Remember that it is good practice to write the classes with the first letter in uppercase, so I would recommend fixing it.

public static void main(String [] args) throws IOException {

    Imagen imagen = new Imagen();
}

The other details that have to be fixed are with respect to the Background image, you should put it better as a BufferedImage since Image as such is an abstract class, if you leave it like this you will get an error. In order to get the image with BufferedImage you do it in the following way:

imagenfondo = ImageIO.read(new FileInputStream(ruta));

and you no longer need URL. Finally, before adding the panel to the container, make sure you have established it as visible.

    
answered by 10.08.2017 в 18:49