Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

macos - Setting the default application icon image in Java swing on OS X

I'm trying to set the icon image for a Jar file:

setIconImage(new ImageIcon(getClass().getResource("logo.png")).getImage());

When running in Mac OS X 10.7.4 I get the following error:

Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextGetCTM: invalid context 0x0
Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextSetBaseCTM: invalid context 0x0
Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextGetCTM: invalid context 0x0
Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextSetBaseCTM: invalid context 0x0
Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextGetCTM: invalid context 0x0
Jun 28 15:21:40 (my dhcp) java[73383] <Error>: CGContextSetBaseCTM: invalid context 0x0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

setIconImage does not set the jar icon. It will set the icon for what the minimized window for that JFrame will look like. The jar icon (which controls the finder icon and the dock application icon) cannot be set in the jar file itself. You just get the default icon provided by the OS. You will need to wrap it using something like JarBundler for OS X or Launch4J for Windows.

You can set the application dock icon while your application is running, see com.apple.eawt.Application.setDockIconImage. It isn't perfect though, because when you double-click on your jar, it starts up in the dock using the generic java icon and only switches to your custom icon after a bounce or two when the java code starts running. Also, I don't think it would set the dock icon for an jar which isn't running (not that you can drag a jar file into the dock anyway - doesn't seem to work for me).

Here's some code that demonstrates the different images you can set:

import com.apple.eawt.Application;
import javax.swing.*;

class SetIcon extends JFrame {

    SetIcon() {
        setIconImage(new ImageIcon("doc.png").getImage());
        Application.getApplication().setDockIconImage(
            new ImageIcon("app.png").getImage());
    }

    public static void main(String args[]) {
        SetIcon s = new SetIcon();
        s.setVisible(true);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...