Social

martes, 29 de abril de 2014

Java: Agregar imagen a botón

En esta entrada se agregara una imagen a un botón en Java. Existen varias formas pero observaremos como hacerlas usando la clase URL para ubicar el archivo que deseamos. Al final obtendremos algo como esto:

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:

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:

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);
}
}

jueves, 24 de abril de 2014

Java: Archivos Temporales

Un ejemplo de como escribir información en un archivo temporal en Java. No existe diferencia entre lo que se puede escribir en un archivo normal y uno temporal. Generalmente los temporales nos sirven cuando queremos crear archivos en un applet.

En este ejemplo se crea el archivo "archivo.tmp" y se le escribe información de dos formas diferentes.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ArchivoTemporal
{
public static void main(String[] args)
{
try{
//Crear un archivo temporal
File temp = File.createTempFile("archivo", ".tmp");
//Le indicamos que lo eleminte cuando se cierre el programa.
temp.deleteOnExit();
//Escribir contenido con BufferedWriter
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write("This is the temporary file content");
bw.close();
/*¨--- ALTERNATIVA ---*/
//Escribir el archivo con un InputStream
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/pack/yourfile");
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[is.available()];
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
is.close();
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}