Can't Change Default Java Image (JFrame.setIconImage) - java

I am trying to change the icon of the Java application but nothing seems to work.
I am trying to get image from resources path using:
getClass().getResource("/AppIcon.png")
Sometimes I get an error like URL not found.

The image that is used for the Form's icon can be any image but must be loaded as an Image type (not of ImageIcon type). The JFrame#setIconImage() method will auto-size the image loaded. Here just a couple ways. These examples assume that the code resides in a class which extends JFrame:
Example #1:
try {
/* For a Form's title bar icon....
Don't use this for animated .gif images otherwise your GUI will
freeze. I'm not exactly sure why but it seems as though the gif
frames continuously cycle as though in an infinite loop. If you
want to use an animated .gif image as a Form's title bar icon
then don't use Toolkit, use ImageIO.read() instead since it will
only utilize the first gif frame as the image. */
// Be sure to set the path string to your specific resources directory.
this.setIconImage(java.awt.Toolkit.getDefaultToolkit()
.getImage(getClass().getResource("/resources/images/Apple/png").getFile()));
}
catch (java.lang.NullPointerException ex) {
// Do what you want with caught exception.
ex.printStackTrace();
}
Example #2:
try {
/* Can be used to also display an animated gif for the Form's Title
bar icon but only the first gif frame is utilized. */
// Be sure to set the path string to your specific resources directory.
File pathToFile = new File(getClass().getResource("/resources/images/Apple.png").getFile());
Image image = ImageIO.read(pathToFile);
this.setIconImage(image);
}
catch (IOException ex) {
// Do what you want with caught exception.
ex.printStackTrace();
}
UPDATE:
As stated by #AndrewThompson in comments, the two above examples will not work as expected from a JAR file. They will work if run through the IDE however which in reality is no good except for testing. To use the two examples above in a distributive JAR file then also see Example #3 and Example #4:
Example #3:
try {
/* For a Form's title bar icon.... To be used in a distributive JAR.
Don't use this for animated .gif images otherwise your GUI will
freeze. I'm not exactly sure why but it seems as though the gif
frames continuously cycle as though in an infinite loop. If you
want to use an animated .gif image as a Form's title bar icon
then don't use Toolkit, use ImageIO.read() instead since it will
only utilize the first gif frame as the image. */
// Be sure to set the path string to your specific resources directory.
java.net.URL url = getClass().getResource("/resources/images/Apple.png");
this.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(url));
}
catch (java.lang.NullPointerException ex) {
// Do what you want with caught exception.
ex.printStackTrace();
}
Example #4:
try {
/* For a Form's title bar icon.... To be used in a distributive JAR.
Can be used to also display an animated gif for the Form's Title
bar icon but only the first gif frame is utilized. */
// Be sure to set the path string to your specific resources directory.
java.net.URL url = getClass().getResource("/resources/images/Apple.png");
Image image = ImageIO.read(url);
this.setIconImage(image);
}
catch (IOException ex) {
// Do what you want with caught exception.
ex.printStackTrace();
}
Don't even bother with Examples #1 and #2, they now just remain here for reference. Just use either Example #3 or Example #4. Both will work in the IDE or a distributive JAR file.

Solution;
Everything works for windows but I am using Mac :D
So I started to look around Taskbar class comes with awt package and found the solution (Thanks to flohall)
try {
var image = new ImageIcon(Objects.requireNonNull(Main.class.getResource("/AppIcon.png")));
frame.setIconImage(image.getImage());
if (System.getProperty("os.name").startsWith("Mac") || System.getProperty("os.name").startsWith("Darwin")) {
Taskbar taskbar = Taskbar.getTaskbar();
try {
taskbar.setIconImage(image.getImage());
} catch (final UnsupportedOperationException e) {
System.out.println("Can't set taskbar icon.");
} catch (final SecurityException e) {
System.out.println("Warning. Can't set taskbar icon due to security exceptions.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
So we are telling the taskbar to change its icon using built-in awt Taskbar class on taskbar.setIconImage(image.getImage());. And that solves most of the things I've needed for.

Related

Why is my JFrame Icon not changing from the default java icon?

I have tried several solutions for changing the icon of my application, but none have worked! I do not get any error when i do the following but it still won't change!? Please, can someone tell me where I am going wrong because i don't see any error, and I am not receiving any error either!
I even made sure that the icon I want to use is a 20x20 pixel icon, because I read somewhere that is the maximum size for an icon.
frame.setIconImage(
new ImageIcon(getClass().getResource("/images/bfc_icon.png")).getImage());
Why is this not working? Any help would be greatly appreciated!
EDIT:
I am testing if the file exists, turns out it does but it still is not being set as the application icon...why is this??
URL url = getClass().getResource("src/images/bfc_icon.png");
if (url == null)
System.out.println( "Could not find image!" );
else
frame.setIconImage(new ImageIcon(url).getImage());
private void formWindowOpened(java.awt.event.WindowEvent evt) {
try {
// TODO add your handling code here:
Image img=ImageIO.read(getClass().getResource("ur path"));
this.setIconImage(img);
} catch (IOException ex) {
}
this will work
It seems a bit too late, but I hope this helps.
This problem probably happens when you called the setIconImage() before you initialize the JFrame.
I also had this problem with the code below (w/ Eclipse IDE):
setIconImage(Toolkit.getDefaultToolkit().getImage(Apps.class.getResource("/ico.png")));
initComponents();
I accidentally solved the problem by swapping these two so it looks like this:
initComponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(Apps.class.getResource("/ico.png")));
You should try to do it as well, at least call the setIconImage() after the JFrame has initialized if you didn't use any window builder tool.
Cheers!
In my case, I just simply copied the picture I want to use as my icon to the project folder and not the src folder (source code folder) and it worked.

Application icon not following the exported project?

My application icon works fine when running the app from Eclipse, but once I export it as a runnable jar, then it doesn't appear.
This is the code I use to set the icon:
try {
setIconImage(ImageIO.read(new File("resources/icons/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
The icon is in a source-folder called resources/icons.
Why doesn't the icon get included in the export?
Using URL now instead of looking for the icon with the File method. This works great!
Is it possible to change - by default - the file's icon? I think I have to use resource hacker or something like that in order to change it. But if it's possible via code, I'd love to learn it!
You can use getResource instead of new File(), like this:
Icon icon = new ImageIcon(getClass().getResource("resources/icons/icon.png"));
So your setIconImage should be like so:
setIconImage(new ImageIcon(getClass().getResource("resources/icons/icon.png")).getImage());
If your icon exit inside your package you can do like this:
Icon icon = new ImageIcon(getClass().getResource("/com/icons/icon.png"));
So your setIconImage should be like so :
setIconImage(new ImageIcon(getClass().getResource("/com/icons/icon.png")).getImage());
Hope this helped.

Selenium - Firefox webdriver will only take partial screenshot

From what I've read the following code:
File s = ((TakesScreenshot)driver_).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(s,new File("C:\\scr.png"));
} catch (IOException exception) {
exception.printStackTrace();
}
Should take a full page screenshot. But in my case it will only take the screenshot of whatever is currently visible in the browser window. Is this the expected behaviour or did something go wrong in the code?
Yes it is expected behavior from firefox.
If you want to take full page screenshot you can use something like this to zoom out the whole contents to visible area
executor = (JavascriptExecutor)driver.getDriver();
executor.executeScript(
"document.body.style.zoom=
(top.window.screen.height-70)/
Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);");
File scrFile = ((TakesScreenshot)driver.getDriver()).getScreenshotAs(OutputType.FILE);
It will try to bring all the content to visible area, although you can still miss some content from the very bottom area.

Java Icon Image Maximum File Size

I am working on a chess game on Java. I have been importing images onto Eclipse and then assigning them to ImageIcons, and then subsequently assigning these ImageIcons onto buttons to form a grid.
At one point three out of my four bishop images were not being assigned to their respective buttons and so I looked at the file size and it turns out that the sizes of the three images that weren't being assigned were ~1,100KB, ~1,200KB, and ~40KB. The image that was being assigned to the button was around 25KB. I thought this was odd (especially since all four images are very similar) so I exported the three problematic images in a lower resolution (all under 30KB), and then re-imported them into Eclipse. When I ran my program again they were assigned to the right buttons and everything ran smoothly again.
The buttons that I am using are all 75 x 75 pixels, and the pixels were the same for each image (75 x 75), so I am confused why this happened. I looked for any questions relating to this, but I could not find any. If anyone could help explain why this could happen to me that would be very helpful so I can avoid this problem in the future.
I've definitely loaded images much bigger than that into ImageIcons and other components, so I suspect that your issue is that when you are assigning the Image to the ImageIcon before the Image is fully loaded. You can use MediaTracker to help solve this problem. From ImageIcon:
/** * Loads an image into memory */
public static Image loadImage(String fn){
try {
Image image=java.awt.Toolkit.getDefaultToolkit().createImage(fn);
MediaTracker tracker=new MediaTracker(lblForFM); tracker.addImage(image,0);
tracker.waitForID(0);
if (MediaTracker.COMPLETE != tracker.statusID(0,false)) throw new
IllegalStateException("Unable to load image from " + fn);
else return image; } catch ( InterruptedException e) {
throw new RuntimeException("Interrupted while loading image from " + fn,e);
}
}
I recommend using png for transparent images and icons, jpg for non-transparent images - and only if compression artifacts don't matter (lossless JPEG sadly isn't widely spread). bmp is one of the worst file formats out there if it comes to file size. As suggested by the others, load images in java with the ImageIO API:
public class Program {
public static void main(String[] args) {
InputStream imageSource = Program.class.getResourceAsStream("bishop"); // may be a URL, File or ImageInputStream instead
try {
BufferedImage bishopImage = ImageIO.read(imageSource); // read image
ImageIcon bishopIcon = new ImageIcon(bishopImage); // use adapter for Icon interface
System.out.println(bishopIcon); // do something with it
} catch (IOException e) {
e.printStackTrace(); // read failed
}
}
}

Loading Images from Web Directory, display in ImageView

I am trying to write a simple application that loads images that are stored in a web directory I've created. I want the application to grab ALL of the images that are stored in said directory and display them in a layout.
The code below works for only certain type of URLs(mainly tinypic, but not photobucket, imageshack etc) and also not for directories.
I've my image names formatted in sequence like image1.png, image2.png, etc. so that the code snippet and the downloadFile()-method would work.
But, I'm not sure how I would grab all the images from the server simultaneously because this only grabs one image at a time, sets it as a bitmap and then displays it in an IV. I'm pretty new to Android so some help in the right direction would be appreciated.
public class NewWallpapersActivity extends Activity {
ImageView imView1;
String imageUrl="http://i133.photobucket.com/albums/q44/slimjady/Wallpapers";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.newwallpapers);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView1 = (ImageView)findViewById(R.id.IV1);
}
View.OnClickListener getImgListener = new View.OnClickListener(){
public void onClick(View view) {
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl = null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView1.setImageBitmap(bmImg);
} catch (IOException e) {
String exception = "Erro: An Exception Was Thrown";
Toast errortoast = Toast.makeText(this, exception, Toast.LENGTH_SHORT);
errortoast.show();
e.printStackTrace();
}
}
}
Here are some thoughts on this one:
Displaying all Images
Since you want to display all Images from within a single folder, I would suggest you to have a Directory-Activity, which displayes all the images in the given directory and one Image-Activity which displays only one single Image.
To proper present this I would suggest using a GridView to display all the Images and a normal Activity with a full-screen ImageView to display the single Image.
You could also use the Gallery-widget to "combine" both those ideas.
Not letting the user wait
One of the bigger problems with your approach is, that the images are getting downloaded on the UI-Thread.
Depending on the size of all or on single image and the available connection-speed, Downloading the image can take a while. While the images are getting downloaded, the UI-Thread will wait for your downloadStuff()-method to return and the UI will freeze. This might create the illusion that your App just crashed.
So, you'll want to do the downloading in a separate thread. Android has a handy wrapper for this called an AsyncTask.
As a little bonus to show your user that the process might take a while you can use a ProgressDialog to illustrate this (on the UI-Thread).
Knowing whats in a directory
Now we come to the point where we have to face some limitations. If you want to use Picture-Hosters like the ones you listed above, you'll need to check if they offer you an API (or something equal) to get a list of Images (or their URLs) from a certain directory/album (look for a "API"-link on the front-page).
If you host the images on your own Server, you should be able to create a little PHP-script (or whatever script/programming language you prefer), which then lists all image-files in the directory and presents them in an easy-to-parse way (either JSON or XML).
This should enable you to get a list of URLs to the Image-files you want to display.

Categories

Resources