I tried looking up multiple tu开发者_运维百科torials on how to change the programs icon in java but none of them seem to work. I was also wondering what kind of image can it be .ico or .png eg and what size it had to be
I assume you're using a JFrame
, then you want setIconImage(java.awt.Image)
:
File/InputStream/URL x = ...
Image icon = ImageIO.read(x);
frame.setIconImage(icon);
The image file format is irrelevant as long as ImageIO can read it (JPEG, GIF, PNG, TIFF, even BMP if really really necessary).
An example:
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Main {
public static void main(final String[] args) throws Exception {
JFrame frame = new JFrame("Custom Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// something off the Google Images front page
final URL url = new URL("http://t3.gstatic.com/images?q=tbn:ANd9GcQbcDkaRcrbsYFUcE6Q7n56_LJr-r4mDqYTOTtPKG9J0MzZcV6V");
frame.setIconImage(ImageIO.read(url));
frame.setVisible(true);
}
}
Edit: How to get a URL to your icon
You should place your image files (icons, etc) along with your source code, maybe into its own sub folder in your src
folder and access them as "resource". Check out How to use Icons from the Java Tutorial for how to get a URL
object to a resource.
I think @Philipp made it quite clear, that x
has to be a File
, InputStream
or URL
, not a String
as it seems you tried.
Now, you also need to have a Frame
or JFrame
to have an icon!
I presume this is in your main
method.
To create a frame try
JFrame frame=new JFrame();
frame.setVisible(true);
followed by @Philipp's code.
--
It just occured to me you might mean the icon of the program shortcut in your operating system. This isn't done in Java but in your operating system. unless you use Java Web start
精彩评论