La imagen puede que se un archivo dentro de nuestro proyecto o con una imagen en la web. Luego simplemente se agrega la imagen al botón por medio de su constructor. El siguente script muestra la forma de hacerlo:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ImageIcon dukesIcon = null; | |
java.net.URL imgURL1 = ImageButton.class.getResource("/img/ReallySmallDuke.png"); | |
//puedes obetner imagenes directamente de la web | |
java.net.URL imgURL2 = null; | |
try{ | |
imgURL2 = new java.net.URL("http://openjdk.java.net/images/duke-thinking.png"); | |
} catch (MalformedURLException e){ | |
System.out.println("URL invalida"); | |
} | |
if (imgURL != null) { | |
dukesIcon = new ImageIcon(imgURL1); //Usa imgURL1 o imgURL2 | |
} else { | |
System.out.println("No se pudo cargar la imagen."); | |
} | |
JButton jButton = new JButton("Ejemplo", dukesIcon); |
Si ponen la imagen dentro de su proyecto es recomendable usar un paquete para guardarlas.
A continuación el código completo de la solución:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.BorderLayout; | |
import javax.swing.BoxLayout; | |
import javax.swing.ImageIcon; | |
import javax.swing.JButton; | |
import javax.swing.JFrame; | |
import javax.swing.JPanel; | |
public class ImageButton extends JFrame { | |
public void crearBoton() { | |
JPanel hPanel = new JPanel(); | |
hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS)); | |
ImageIcon dukesIcon = null; | |
java.net.URL imgURL1 = ImageButton.class.getResource("/img/ReallySmallDuke.png"); | |
//puedes obetner imagenes directamente de la web | |
java.net.URL imgURL2 = null; | |
try{ | |
imgURL2 = new java.net.URL("http://openjdk.java.net/images/duke-thinking.png"); | |
} catch (MalformedURLException e){ | |
System.out.println("URL invalida"); | |
} | |
if (imgURL != null) { | |
dukesIcon = new ImageIcon(imgURL1); //Usa imgURL1 o imgURL2 | |
} else { | |
System.out.println("No se pudo cargar la imagen."); | |
} | |
JButton jButton = new JButton("Ejemplo", | |
dukesIcon); | |
jButton.setVerticalTextPosition(JButton.BOTTOM); | |
jButton.setHorizontalTextPosition(JButton.RIGHT); | |
hPanel.add(jButton); | |
getContentPane().add(hPanel, BorderLayout.CENTER); | |
} | |
public static void main(String[] args) { | |
mostrarGUI(); | |
} | |
private static void mostrarGUI() { | |
ImageButton boton = new ImageButton(); | |
boton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
boton.crearBoton(); | |
boton.pack(); | |
boton.setVisible(true); | |
} | |
} |
Agregar imagen de internet a botón en Java.
ResponderEliminar