Resource loading problen in Java - 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.

Related

Java Swing Icon wont show up [duplicate]

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.

How do I add an image with this code?

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.sound.midi.Patch;
import javax.swing.*;
this is were the code start
public class graficCar extends JComponent
{
private ImageIcon image1=null;
private JLabel label1=null;
private ImageIcon image2=null;
private JLabel label2=null;
graficCar(){
setLayout(new FlowLayout());
the problem here
image1=new ImageIcon(getClass().getResource("4596067.png"));
label1=new JLabel(image1);
add(label1);
}
the main
public static void main(String[] args)
{
graficCar g=new graficCar();
g.setDebugGraphicsOptions(JFrame.EXIT_ON_CLOSE);
g.setVisible(true);
}
As you mentioned, your png file is in C:\Users\user\Downloads folder. I bet class is somewhere else.
The problem is getResource() finds file in classpath by default. Here you could find details if you want to go deeper.
One solution is to put .png right next to your .java class but it's bad practice. More convenient way described here. The best practice is to create special folder for your resources in the project and then use relative path to it. How to do this is out of scope although it's described in many sites and in Stackoverflow too. Don't hesistate to use Search :)

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");

Icon not showing when jar file is run

I'm a beginner in Java and I followed a tutorial to write this program (yes, I that much of a beginner) and it works perfectly when I run it on Eclipse. It also runs great on the computer I coded it on. However, if I send it to another computer (just the .jar file) and run it, it fails because it can't find the icon. Here is everything I've got. The icon I'm using is saved in the bin folder along with all the class files for the program. For privacy reasons, I replaced certain lines with "WORDS".
The tutorial I followed in two parts:
Part 1 - https://buckysroom.org/videos.php?cat=31&video=18027
Part 2 - https://buckysroom.org/videos.php?cat=31&video=18028
My main class (I called it apples cause the tutorial did).
import javax.swing.JFrame;
public class apples {
public static void main(String[] args) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(1920,1080);
go.setVisible(true);
}
}
And now my second class, "Gui":
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Gui extends JFrame {
private JButton custom;
public Gui () {
super("WORDS");
setLayout(new FlowLayout());
Icon b = new ImageIcon(getClass().getResource("b.png"));
custom = new JButton(null, b);
custom.setToolTipText("WORDS");
add(custom);
HandlerClass handler = new HandlerClass();
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
}
}
}
Thank you so much for helping!
It's worth reading Loading Images Using getResource where it's explained in detail along with loading images from jar as well.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("b.png"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/b.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/b.png"))
Read more...

Bringing custom splash screen to custom about box in NetBeans platform applications

Am trying to create a NetBeans platform application. I created my own splash screen. The splash screen appears in the default about box.
But when I customized the about box, the default splash screen of NetBeans appears.
This is the location of my splash img.
branding/core/core.jar/org/netbeans/core/startup/splash.gif
This is how I have tried to access it and failed.
getClass().getResource("/org/netbeans/core/startup/splash.gif")
Can someone please help me in getting my splash img in the custom about box?
Yes, it is easy. Just right click to project - application, -> branding -> splash scree -> browse. ..
I am sorry for misunderstanding.
So it is easy too.
1) you modify App/important files/project properties add this line:
#for run
run.args=-J-Dnetbeans.mainclass=splah.CustomStartup --nosplash
#for run from IDE
run.args.extra=-J-Dnetbeans.mainclass=splah.CustomStartup --nosplash
2)create project JavaApplication splah and class CustomStartup, then build and copy the jar from dist to App/
package splah;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.lang.reflect.Method;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JWindow;
public class CustomStartup {
private static final String NB_MAIN_CLASS = "org.netbeans.core.startup.Main";
private static final int width = 500, height = 400;
public static void main(String[] args) throws Exception {
// do whatever you need here (e.g. show a custom login form)
System.out.println("Hello world! I am a custom startup class");
JDialog splash = new JDialog();
splash.setUndecorated(true);
//
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
splash.setBounds(width, height, (screenSize.width-width)/2, (screenSize.height-height)/2);
splash.setVisible(true);
// once you're done with that, hand control back to NetBeans
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
Class<?> mainClass = Class.forName(NB_MAIN_CLASS, true, classloader);
Object mainObject = mainClass.newInstance();
Method mainMethod = mainClass.getDeclaredMethod("main", new Class[]{String[].class});
mainMethod.invoke(mainObject, (Object) args);
splash.setVisible(false);
}
}
The Class is not from my head, I found it somewhere, but I do not remeber where.
Jirka

Categories