Search code examples
javaswingimageicontaskbar

Taskbar icon with multi frame app in Swing Java


I have a Java Swing application where several frames could be opened at once. Each of the frames has its own icon image. How does it determined by OS which of the icons should be used in the task bar. And is there any way to switch the icon to another frame' icon?


Solution

  • Given JFrame 1, JFrame 2 and JFrame 3 each one with its respective icon:

    The setIcons method:

    public void setIcons(List<JFrame> frames, Image icon) {
        List<Image> iconAsList = new ArrayList<Image>();
        iconAsList.add(icon);
        for(JFrame frame: frames) {
            frame.setIconImages(iconAsList);
        }
    }
    

    Other code:

    ...
    List<JFrame> frames = new ArrayList<JFrame>();
    JFrame frame1 = new JFrame();
    JFrame frame2 = new JFrame();
    JFrame frame3 = new JFrame();
    Image icon1 = new ImageIcon("icon1.png").getImage();
    Image icon2 = new ImageIcon("icon2.png").getImage();
    Image icon3 = new ImageIcon("icon3.png").getImage();
    
    frames.add(frame1);
    frames.add(frame2);
    frames.add(frame3);
    
    setIcons(frames, icon1); //Set all frames to use icon 1
    
    //DO OTHER STUFF
    
    setIcons(frames, icon3); //Set all frames to use icon 3
    ...
    

    Let me know if this helps.