3

I want to add an image (small icon) to the javax.swing.JFrame title bar.

How can I do it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DarRay
  • 2,550
  • 6
  • 27
  • 39

1 Answers1

12

Since JPanel doesn't have a title bar, I'm assuming that you're referring to JFrame. That being said, use setIconImage(...).


Here is an example of using setIconImages().

import java.awt.Image;
import javax.swing.*;
import javax.imageio.ImageIO;

import java.net.URL;
import java.util.*;

class FrameIcons {

    public static void main(String[] args) throws Exception {
        URL url16 = new URL("https://i.stack.imgur.com/m0KKu.png");
        URL url32 = new URL("https://i.stack.imgur.com/LVVMb.png");

        final List<Image> icons = new ArrayList<Image>();
        icons.add(ImageIO.read(url16));
        icons.add(ImageIO.read(url32));

        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JFrame f = new JFrame("Frame Icons");
                f.setIconImages(icons);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLocationByPlatform(true);
                f.setSize(200,100);
                f.setVisible(true);
            }
        });
    }
}

Frame using 16x16 icon

enter image description here

Application tabbing using the 32x32 icon

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
mre
  • 43,520
  • 33
  • 120
  • 170
  • 4
    ..see also related method `setIconImages()` (note the plural form). If you set images of size 16x16 & 32x32, the 1st will be used as the frame icon (on systems that support it - I noted recently that the Mac. does not), & the second displayed when 'alt tabbing' between different applications. I have no idea which other platforms besides Windows display an icon to represent apps. when changing between them. – Andrew Thompson Jun 19 '11 at 17:29
  • 2
    @mre: I could not resist adding an example using a couple of images borrowed from another thread about these parts. I figured it was best to add it as an edit to your question, since it is effectively the same answer. If you prefer, edit it out & I'll add it as a separate answer. – Andrew Thompson Jun 19 '11 at 17:59
  • 2
    @Andrew, this is perfect. I appreciate the detailed elaboration you provided...it definitely enriches the value of this answer. kudos to you! :) – mre Jun 19 '11 at 18:01
  • 1
    @mre: A nice adjunct to (what I believe is) the 'answer to the *right* question'. ;) – Andrew Thompson Jun 19 '11 at 18:11
  • @mre: thanks for the details well structured ans.. With your help i found that the thing suitable for me is the Inner Frames. Thanks again for your great answer... – DarRay Jun 19 '11 at 18:42