2009-10-23 30 views
87

Tengo un JFrame que muestra un icono de Java en la barra de título (esquina izquierda). Quiero cambiar ese icono a mi icono personalizado. ¿Cómo debería hacerlo?Cómo cambiar el icono de JFrame

+10

Apuesto a que en la mayoría de los casos esas personas ni siquiera han oído hablar de la API. Probablemente la mejor solución en casos como este es proporcionar un enlace a la API con la respuesta. – Carlos

Respuesta

130

Crear un nuevo ImageIcon objeto como éste:

ImageIcon img = new ImageIcon(pathToFileOnDisk); 

luego otra vez en su JFrame con setIconImage():

myFrame.setIconImage(img.getImage()); 

también comprobación setIconImages() que toma un List lugar.

+0

¿Cuál debería ser el tamaño del ícono? ... voy a crear uno ahora .. – Anand

+3

Consulte aquí para obtener información interesante sobre el tamaño: http://www.coderanch.com/t/343726/Swing-AWT-SWT-JFace/ java/Frame-s-setIconImage-optimum-image – BFree

+0

Puede haber diferentes valores de tamaño necesarios: [Tamaños de los iconos de cuadro utilizados en Swing] (http://stackoverflow.com/q/18224184/3453226) –

6

JFrame.setIconImage(Image image) bastante estándar.

+13

Estas soluciones no funcionan. –

3

Aquí es cómo lo hago:

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import java.io.File; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 



public class MainFrame implements ActionListener{ 

/** 
* 
*/ 


/** 
* @param args 
*/ 
public static void main(String[] args) { 
    String appdata = System.getenv("APPDATA"); 
    String iconPath = appdata + "\\JAPP_icon.png"; 
    File icon = new File(iconPath); 

    if(!icon.exists()){ 
     FileDownloaderNEW fd = new FileDownloaderNEW(); 
     fd.download("http://icons.iconarchive.com/icons/artua/mac/512/Setting-icon.png", iconPath, false, false); 
    } 
     JFrame frm = new JFrame("Test"); 
     ImageIcon imgicon = new ImageIcon(iconPath); 
     JButton bttn = new JButton("Kill"); 
     MainFrame frame = new MainFrame(); 
     bttn.addActionListener(frame); 
     frm.add(bttn); 
     frm.setIconImage(imgicon.getImage()); 
     frm.setSize(100, 100); 
     frm.setVisible(true); 


} 

@Override 
public void actionPerformed(ActionEvent e) { 
    System.exit(0); 

} 

} 

y aquí está el programa de descarga:

import java.awt.GridLayout; 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileOutputStream; 

import java.net.HttpURLConnection; 
import java.net.URL; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JProgressBar; 

public class FileDownloaderNEW extends JFrame { 
    private static final long serialVersionUID = 1L; 

    public static void download(String a1, String a2, boolean showUI, boolean exit) 
    throws Exception 
    { 

    String site = a1; 
    String filename = a2; 
    JFrame frm = new JFrame("Download Progress"); 
    JProgressBar current = new JProgressBar(0, 100); 
    JProgressBar DownloadProg = new JProgressBar(0, 100); 
    JLabel downloadSize = new JLabel(); 
    current.setSize(50, 50); 
    current.setValue(43); 
    current.setStringPainted(true); 
    frm.add(downloadSize); 
    frm.add(current); 
    frm.add(DownloadProg); 
    frm.setVisible(showUI); 
    frm.setLayout(new GridLayout(1, 3, 5, 5)); 
    frm.pack(); 
    frm.setDefaultCloseOperation(3); 
    try 
    { 
     URL url = new URL(site); 
     HttpURLConnection connection = 
     (HttpURLConnection)url.openConnection(); 
     int filesize = connection.getContentLength(); 
     float totalDataRead = 0.0F; 
     BufferedInputStream in = new  BufferedInputStream(connection.getInputStream()); 
     FileOutputStream fos = new FileOutputStream(filename); 
     BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); 
     byte[] data = new byte[1024]; 
     int i = 0; 
     while ((i = in.read(data, 0, 1024)) >= 0) 
     { 
     totalDataRead += i; 
     float prog = 100.0F - totalDataRead * 100.0F/filesize; 
     DownloadProg.setValue((int)prog); 
     bout.write(data, 0, i); 
     float Percent = totalDataRead * 100.0F/filesize; 
     current.setValue((int)Percent); 
     double kbSize = filesize/1000; 

     String unit = "kb"; 
     double Size; 
     if (kbSize > 999.0D) { 
      Size = kbSize/1000.0D; 
      unit = "mb"; 
     } else { 
      Size = kbSize; 
     } 
     downloadSize.setText("Filesize: " + Double.toString(Size) + unit); 
     } 
     bout.close(); 
     in.close(); 
     System.out.println("Took " + System.nanoTime()/1000000000L/10000L + "  seconds"); 
    } 
    catch (Exception e) 
    { 
     JOptionPane.showConfirmDialog(
     null, e.getMessage(), "Error", 
     -1); 
    } finally { 
     if(exit = true){ 
      System.exit(128); 
     } 

    } 
    } 
} 
+0

'imgicon.getImage() 'es lo que necesitaba gracias – shareef

14

Aquí es una alternativa que funcionó para mí:

yourFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath))); 

Es muy similar a la respuesta aceptada.

+4

El único que responde cómo usar la imagen si es un recurso. : D –

3

Desafortunadamente, la solución anterior no funcionaba para el plugin Jython Fiji. Tuve que usar getProperty para construir dinámicamente la ruta relativa.

Esto es lo que funcionó para mí:

import java.lang.System.getProperty; 
import javax.swing.JFrame; 
import javax.swing.ImageIcon; 

frame = JFrame("Test") 
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png') 
frame.setIconImage(icon.getImage()); 
frame.setVisible(True) 
+0

¿Qué es jthon? @otterb – gumuruh

+0

Jython es Python implementado con java – otterb

1

Apenas añada el siguiente código:

setIconImage (nueva ImageIcon (PathOfFile) .getImage());

0

Esto hizo el truco en mi caso super o this referes a JFrame en mi clase

URL url = getClass().getResource("gfx/hi_20px.png"); 
ImageIcon imgicon = new ImageIcon(url); 
super.setIconImage(imgicon.getImage()); 
+0

No necesita el super o esto en su caso. Puedes dejarlo fuera. – creativecreatorormaybenot

+0

puede estar en lo cierto, depende de su diseño de herencia – shareef

+1

Si amplía su clase, no es realmente necesario. – creativecreatorormaybenot

0

Agregue el código siguiente en el constructor de este modo:

public Calculator() { 
    initComponents(); 
//the code to be added  this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage());  } 

Cambio "color.png" al nombre de archivo de la imagen que desea insertar. Arrastre y suelte esta imagen en el paquete (en Paquetes de origen) de su proyecto.

Ejecute su proyecto.

Cuestiones relacionadas