How to change JFrame icon [duplicate]
Asked Answered
C

8

129

I have a JFrame that displays a Java icon on the title bar (left corner). I want to change that icon to my custom icon. How should I do it?

Colton answered 23/10, 2009 at 17:11 Comment(1)
I bet that in the most cases those people have not even heard of the API yet. Probably the best solution in cases like this is to provide a link to the API with the answer.Calen
P
192

Create a new ImageIcon object like this:

ImageIcon img = new ImageIcon(pathToFileOnDisk);

Then set it to your JFrame with setIconImage():

myFrame.setIconImage(img.getImage());

Also checkout setIconImages() which takes a List instead.

Plasterboard answered 23/10, 2009 at 17:15 Comment(4)
what should be the size of the icon?.. im gonna create one now ..Colton
See here for interesting discussion about size: coderanch.com/t/343726/Swing-AWT-SWT-JFace/java/…Plasterboard
There may be different size values needed: Sizes of frame icons used in SwingHayne
You can set titlebar icon using setIconImage() of JFrame and image must be .png fileConductance
B
33

Here is an Alternative that worked for me:

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

It's very similar to the accepted Answer.

Bresnahan answered 18/6, 2014 at 9:24 Comment(2)
The only one which answers how to use the image if it's a resource. :DElongate
Example for the filepath: The image is in "myProject/res" -> getClass().getResource("/myimage.png") (don't forget the leading "/"!)Luxurious
B
6

JFrame.setIconImage(Image image) pretty standard.

Blatherskite answered 23/10, 2009 at 17:15 Comment(1)
These solutions do not work.Bedcover
M
5

Here is how I do it:

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

}

}

and here is the 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);   
        }

    }
  }
}
Misdeed answered 9/6, 2013 at 16:58 Comment(1)
imgicon.getImage() is what i needed thanksNam
F
4

Just add the following code:

setIconImage(new ImageIcon(PathOfFile).getImage());
Foah answered 26/2, 2016 at 5:25 Comment(0)
H
2

Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.

Here's what worked for 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)
Hillside answered 4/3, 2015 at 15:18 Comment(2)
what is jthon? @HillsideGeothermal
Jython is Python implemented with javaHillside
N
1

This did the trick in my case super or this referes to JFrame in my class

URL url = getClass().getResource("gfx/hi_20px.png");
ImageIcon imgicon = new ImageIcon(url);
super.setIconImage(imgicon.getImage());
Nam answered 14/5, 2016 at 8:7 Comment(5)
You don't need the super or this in your case. You can leave it out.Imagism
may be you are right it depends on your inheritance designNam
If you extend your class it is not really necessary.Imagism
as i remember i think i had inner classes with same method which make thing ambigous but yor assumption is the default i agreeNam
Yes you are right. That is why I said it's not necessary, because it has to be done sometimes if you wan't two have a method with the same name ^^Imagism
P
-1

Add the following code within the constructor like so:

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

Change "color.png" to the file name of the picture you want to insert. Drag and drop this picture onto the package (under Source Packages) of your project.

Run your project.

Prone answered 16/6, 2016 at 3:15 Comment(1)
You can set titlebar icon using setIconImage() of JFrame and image must be .png fileConductance

© 2022 - 2024 — McMap. All rights reserved.