Domanda

i have in my applications jframe Hide on close, but when i click the dock icon, i want it to setVisible(true); how do i add an action listener to the dock icon? i tried

Image im = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("SLogo.png"));
final TrayIcon tri = new TrayIcon(im);
tri.addActionListener(this);

@Override
public void actionPerformed(ActionEvent ae) {
     this.setVisible(true);
     System.out.print("ok");

}

but its not triggered, and also, how will it affect the app on windows machine?

È stato utile?

Soluzione

You need to use an AppForegroundListener and/or AppReOpenedListener. See this example:

public static void main(String[] args)
{
    final JFrame frame = new JFrame();

    Application app = Application.getApplication();
    app.addAppEventListener(new AppForegroundListener() {

        @Override
        public void appMovedToBackground(AppForegroundEvent arg0)
        {
            System.out.println("appMovedToBackground");
        }

        @Override
        public void appRaisedToForeground(AppForegroundEvent arg0)
        {
            System.out.println("appRaisedToForeground");
            frame.setVisible(true);
        }

    });

    app.addAppEventListener(new AppReOpenedListener() {
        @Override
        public void appReOpened(AppReOpenedEvent arg0)
        {
            System.out.println("app reoponed");
            frame.setVisible(true);
        }
    });

    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
}

If you develop on Windows, you'll need to include stubs of the Mac/Java classes or else you'll get compiler errors. See here.

If you develop on Mac, just make sure the code is not executed when running on Windows.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top