Home > Enterprise >  My program in java doesn´t show the image
My program in java doesn´t show the image

Time:11-02

`

package primero.ventanona;

import java.awt.Container;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Ventanona extends JFrame{
JButton boton;
ImageIcon imagen;
Icon icono;
public Ventanona(){
    this.setBounds(0, 0, 400, 400);
    this.setTitle("HOLA");
    Container contentpane = getContentPane();
    contentpane.setLayout(null);
    this.setVisible(true);
    boton = new JButton();
    boton.setBounds(0, 0, 80, 80);
    imagen = new ImageIcon("icono.png");
    icono = new ImageIcon(imagen.getImage().getScaledInstance(boton.getWidth(), boton.getHeight(), Image.SCALE_DEFAULT));
    boton.setIcon(icono);
    contentpane.add(boton);
}
    public static void main(String[] args) {
        Ventanona ventanita = new Ventanona();
    }
}

`

I have this program where I need to display an image on the button, but when I run the program it only shows a blue square and not the image.

CodePudding user response:

oops thats gonna be an issue right

CodePudding user response:

To use image/icon in swing, you can setup folder structure as below :

src/
----images
----icons
----your-folder/Ventanona.java

Inside Ventanona.java can access :

new ImageIcon(getClass().getResource("/images/icono.png"))

Hope that helps you !

  • Related