Matthias
Matthias

Reputation: 10379

Howto dynamically enable or disable taskbar icon for a Java Swing program

I am writing a Java Swing-based program using and JFrame that is able to display a system tray icon for quick access to most-used features. Now I want to add an option for the user to choose whether or not the normal (Windows) taskbar icon should be displayed when the program window is minimized.

A search in Google told me that I can use JDialog instead of JFrame. Unfortunately that is not a good solution in my case, because I want to dynamically enable or disable the task bar icon based on the user's decision.

Is that possible somehow?

Thanks and kind regards, Matthias

Upvotes: 1

Views: 4664

Answers (2)

phill
phill

Reputation: 486

Something to try, though I am not entirely sure this will work becase it is late here and I may be thinking about this the wrong way.

When you minimize a window, an event is triggered, what you want to do is catch it by adding a WindowStateListener to the JFrame that watches for WINDOW_ICONIFIED and WINDOW_DEICONIFIED. When WINDOW_ICONIFIED occurs, set the visible property of the JFrame to false; when WINDOW_DEICONIFIED set it to true. A quick test of setting a frames visibility to false seemed to remove it from the task bar, all you have to do is figure out if it does actually work and then implement a state listner.

Here is the code I used to test

import java.awt.*;

public class FrameTest
{
    public static void main (String args[]) throws Exception
    {
        // Create a test frame
        Frame frame = new Frame("Hello");
        frame.add ( new Label("Minimize demo") );
        frame.pack();

        // Show the frame
        frame.setVisible (true);

        // Sleep for 5 seconds, then minimize
        Thread.sleep (5000);
        frame.setState ( Frame.ICONIFIED );
        frame.setVisible(false);
        // Sleep for 5 seconds, then restore
        Thread.sleep (5000);
        frame.setState ( Frame.NORMAL );
        frame.setVisible(true);

        // Sleep for 5 seconds, then kill window
        Thread.sleep (5000);
        frame.setVisible (false);
        frame.dispose();

        // Terminate test
        System.exit(0);
    }
}

Upvotes: 0

jzd
jzd

Reputation: 23629

A JDialog or JFrame is just a container. Would switching between them not work for your situation? When you need to switch, just create a new instance of the other type set to the same location and size, and move the contentPane over.

Upvotes: 2

Related Questions