2009-10-23 14 views
87

Ho un JFrame che visualizza un'icona Java sulla barra del titolo (angolo sinistro). Voglio cambiare quell'icona alla mia icona personalizzata. Come dovrei farlo?Come modificare l'icona JFrame

+10

Scommetto che nella maggior parte dei casi queste persone non hanno ancora sentito parlare dell'API. Probabilmente la soluzione migliore in casi come questo è di fornire un link all'API con la risposta. – Carlos

risposta

130

Creare un nuovo ImageIcon oggetto come questo:

ImageIcon img = new ImageIcon(pathToFileOnDisk); 

quindi impostarlo al vostro JFrame con setIconImage():

myFrame.setIconImage(img.getImage()); 

checkout anche setIconImages() che prende un List invece.

+0

quale dovrebbe essere la dimensione dell'icona? .. sto per crearne uno ora .. – Anand

+3

Vedi qui per una discussione interessante sulla dimensione: http://www.coderanch.com/t/343726/Swing-AWT-SWT-JFace/ java/frame-s-setIconImage-ottimale immagine – BFree

+0

ci possono essere valori differenti di formato necessari: [Formati di icone cornice utilizzati in swing] (http://stackoverflow.com/q/18224184/3453226) –

6

JFrame.setIconImage(Image image) piuttosto standard.

+13

Queste soluzioni non funzionano. –

3

Ecco come lo faccio:

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

} 

} 

e qui è il downloader:

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() 'è ciò di cui avevo bisogno grazie – shareef

14

Qui è un'alternativa che ha funzionato per me:

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

è molto simile alla risposta accettata.

+4

L'unico che risponde come usare l'immagine se si tratta di una risorsa. : D –

3

Sfortunatamente, la soluzione di cui sopra non funzionava con il plugin Jython Fiji. Ho dovuto usare getProperty per costruire dinamicamente il percorso relativo.

Ecco cosa ha funzionato per me:

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

cos'è jthon? @otterb – gumuruh

+0

Jython è implementato in Python con java – otterb

1

basta aggiungere il seguente codice:

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

0

Questo ha fatto il trucco nel mio caso super o this referes a JFrame nella mia classe

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

Non hai bisogno del super o di questo nel tuo caso. Puoi lasciarlo fuori. – creativecreatorormaybenot

+0

potrebbe essere che tu abbia ragione dipende dal tuo disegno di ereditarietà – shareef

+1

Se estendi la tua classe non è veramente necessario. – creativecreatorormaybenot

0

Aggiungere il seguente codice all'interno del costruttore in questo modo:

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

Change "color.png" al nome del file dell'immagine che si desidera inserire. Trascina e rilascia questa immagine sul pacchetto (sotto Pacchetti sorgente) del tuo progetto.

Esegui il tuo progetto.