Displaying an imageicon in eclipse doesn't work - java

So I've just written down some simple code that just displays an image in a JButton.
What I have done is write the code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static ImageIcon bf;
public static JPanel p;
public static JButton b;
public static void main (String args[]){
Main main = new Main();
bf = new ImageIcon("car.png");
p = new JPanel();
b = new JButton(bf);
p.add(b);
main.add(p);
main.setVisible(true);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setSize(600,700);
}
}
And I have copied a pic named car.png in the same folder with my class, but I can't seem to get it to work in elipse.
But when I run the same exact code in BlueJ it runs it without any known issues.
Any help woul be greately apprecciated
Thanks In advance.

change
bf = new ImageIcon("car.png");
to
URL url = Main.class.getResource("car.png");
bf = new ImageIcon(url);

Check that if car.png is under the bin directory in the filesystem (it is filtered out in Eclipse, so do it in a file explorer).
Btw I would suggest using something like ImageIO.read(Main.class.getResource("/car.png")). The reason is the following: later on you will probably package your app (into a Jar file for example). Now if you do it this way, Java is able to locate the image even if it is executed as a Jar or from

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.

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