Java Swing Icon wont show up [duplicate] - java

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());

Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.

Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));

Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.

This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));

Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));

Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}

Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());

I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.

I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());

My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}

frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/

public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Related

Resource loading problen in Java

I am new to Java and am having a problem with my JAR file loading some graphic resources. I am using IntelliJ IDEA 2021.2 (Ultimate Edition) to write my code. While in the IDE, the code work fine and the resources are loaded, but once I create the JAR file, and run it, thew graphics don't show. I should mention I do have some graphics that show, as explained below:
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class ClassTopFrame extends JPanel{
public ClassTopFrame(int screenWidth, int screenHeight) {
this.setBackground(Color.BLACK);
this.setBounds(160, 0, screenWidth-160, screenHeight/2);
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(Objects.requireNonNull(getClass().getResource("/i_TMEA-0002-J_Logo.png"))));
this.add(jl);
}
}
This class load the image as expected. However when I try to load button images for my menu, the buttoin images do not load. Here is the class I use to create my buttons.
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
public class TMButton extends JButton {
Font okuda;
public TMButton(String text, String color) {
try {
okuda = Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")).deriveFont(16.0F);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")));
} catch (IOException | FontFormatException ignored){
}
ImageIcon defaultIcon = new ImageIcon("res/b_" + color + "_default.png");
ImageIcon hoverIcon = new ImageIcon("res/b_" + color + "_selected.png");
ImageIcon disabledIcon = new ImageIcon("res/b_disabled.png");
this.setForeground(Color.BLACK);
this.setFont(okuda);
this.setText("<html><body><br><br>"+text+"</body><html>");
this.setHorizontalTextPosition(SwingConstants.CENTER);
this.setVerticalTextPosition(SwingConstants.CENTER);
this.setIcon(defaultIcon);
this.setSelectedIcon(hoverIcon);
this.setDisabledIcon(disabledIcon);
this.setMinimumSize(new Dimension(124,70));
this.setBorder(null);
this.setBorderPainted(false);
this.validate();
}
}
As I said, I am baffled as to why this is not working. I am not sure if my project structure is wrong, or if I am creating my JAR file incorrectly. To create the JAR file I am going to IntelliJ's project structure option and creating an Artifact. After I build the Artifact, I set the executable bit in my systems file explorer, and run the far file.
I would appreciate any help anyone can suggest. If I have left something out in my explanation of the problem, I have my entire app post on my GitHub page at: https://github.com/troy-marker/TMEA-0002-J.
Thanks for any assistance, Troy.
Problem is solved. Thank you to g00se for pointing out my error.
In one case, you're filling the image icons with resources, and the other you're filling them with files. You should use the former method at all times
I was trying to load the graphics two different ways, and did not realize it. Thank you for the help.

File Path Changing on Export

I'm currently trying to develop a game, and the file path is changing when I export it.
Here is the code:
package random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Troll extends JFrame{
/**
*
*/
private static final long serialVersionUID = 4176461585360667597L;
public static BufferedImage img;
public static void main(String[] args){
File f = new File("troll.png");
try{
if(f.exists()){
System.out.println("ITS THERE! :D");
img = ImageIO.read(f);
} else {
System.out.println("DOESNT EXIST, REAL PATH IS: " + f.getAbsolutePath() );
}
}catch(Exception e){
e.printStackTrace();
}
new Troll();
}
public Troll(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g){
g.drawImage(img, 500, 350, this);
}
}
When I run it through Eclipse ( The IDE I'm using ), it's running fine and it's showing the image. When I export it as a jar and convert it to an exe using Jar2Exe Software, the image does not appear and in the console it says that the absolute path for the image is on my Desktop. But when I open the exe using 7-Zip, the picture is in the exe.
How can I export it so that when the user runs it, the program can find the file path and show the image, instead of it thinking that it's on my desktop?
If you want to publish it as a jar then you need to use the Jar-specific API for reading your file. See eg. How to read a file from a jar file? (and you need to configure Eclipse to put the picture in the jar, which it sounds like you're already doing).
Also you should let us know whether it works when it's in a jar but not as an exe, that will help us narrow down where the problem may be.
I hope this is not a troll (lol)
img = ImageIO.read(this.getClass().getResource("/troll.jpg"));
You are in a jar, there is no resource file.
See that link as well: http://www.jar2exe.com/createdexe/integrate/protect
Thread.currentThread().getContextClassLoader().getResource("hello/yes.gif");

Change the default Java icon [duplicate]

I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
/** Creates new form Java Program1*/
public Java Program1()
Image im = null;
try {
im = ImageIO.read(getClass().getResource("/image location"));
} catch (IOException ex) {
Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
}
setIconImage(im);
This is what I used in the GUI in netbeans and it worked perfectly
In a class that extends a javax.swing.JFrame use method setIconImage.
this.setIconImage(new ImageIcon(getClass().getResource("/resource/icon.png")).getImage());
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
inside frame constructor
try{
setIconImage(ImageIO.read(new File("./images/icon.png")));
}
catch (Exception ex){
//do something
}
Example:
URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");
btnReport.setIcon(iChing);
System.out.println(imageURL);

JLabel doesn't show image

I'm not sure where the problem is. Is it in the path? The image doesn't show although there are no errors at all in the code syntax. Should I provide the whole path or just place the image in the directory and call its name? Thank you.
public class NetworkingGame {
private JFrame jfrm;
NetworkingGame(){
jfrm = new JFrame("Angry Painters");
jfrm.setSize(800, 480);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
}// end of constructor
public void ImageLoading(){
ImageIcon i = new ImageIcon("C:/Users/TOSHIBA/Documents/NetBeansProjects/NetworkingGame/build/classes/angry-painters.jpeg");
JLabel jl = new JLabel(i);
jfrm.add(jl);
}
public static void main(String[] args) throws Exception{
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
NetworkingGame ng = new NetworkingGame();
ng.ImageLoading();
} // end of run method
}); // end of Runnable
}//end of main method
}//end of class NetworkingGame
Do not use the file path as icon location as this will only work on your computer. You really cannot expect all machines in the world to have C:/Users/TOSHIBA ...angry-painters.jpeg in the right place!
Copy the file next to the source code (.java) class you use and then call
new ImageIcon(getClass().getResource("angry-painters.jpeg"));
The builder should copy the image resource to the class folder itself.
Try to use path something like this :
jLabel1.setIcon(new ImageIcon("c:\\Users\\xyz\\Documents\\NetBeansProjects\\game\\src\\images.jpg"));
Update
If dis also does not work, then
jLabel.setIcon(new ImageIcon(getClass().getResource("/image.jpg")));
jLabel.setText("jLabel");
should.The image.jpg should be inside your project folder.
I think your code doesn't like the way your binding the image.
assumes that your put the images/icons in the source folder
ImageIcon i=new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
or if you create a folder in the source folder
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
BufferedImage bufferedImage=ImageIO.read(stream);
ImageIcon icon= new ImageIcon(bufferedImage);
in IntellijIdea. 2021
In my case it just didn't read image files.
To fix that:
1. make res folder in project root('src's folder sibling)
2. Handle artifact in File->Project Structure->artifacts by + , -
3. File->Project Structure->artifacts->output layout tab make structure of final jar as 'res' folder , app root package folder(say 'com'), and 'META-INF' folder. Fill out them with content from yourapp/output folder and 'res's content from mentioned in 1. step 'res'.
4. After that in 'project structure' 'Modules' rightclick on 'res' and mark it as resources.
5. Declare images like this:
ImageIcon loadingLcl = new ImageIcon(this.getClass().getResource("/res/32.gif"));
before putting into JLabel.
Also it s preferable to read image once when initializing the app. Otherwise sometimes it can throw IOException. So if possible handle that at start. Like they do in gamemaking.

ImageIcon lost after creating a runnable JAR file

The project runs fine when I click play in Eclipse but after I created the runnable JAR file, The ImageIcon for the button is gone.
The images are stored within the src folder, uder a subfolder images.
I created the image icon as
Icon playIcon = (Icon) new ImageIcon("src/images/play.png");
Although I am using a relative path, the button does not display images, How do I get the images even in the JAR file?
Update after Nikolay Kuznetsov's answer
I ended up creating a very unstructured monolithic code for screen recorder and now it is slightly difficult to implement what he said.
I was wondering if there is a way like creating a class or interface that will contain all these resources.
For example:
public class embeddedResources {
public static Icon blackCursor;
public static Icon whiteCursor;
...
...
}
Then all I have to do is import these statics and in my main ScreenRecorder class,
this.blackCursor = embeddedResources.blackCorsor;
I am using this method to read image into BufferedImage where IconManager is class where it is defined.
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
I had the same problem.
Try to make you JAR file and add your images to an extern folder.
So you have a folder "Game" in this folder are the folder for your images called "images" or so and your jar file.
If you now edit you folder path to "../images/play.png" it should work.

Categories