Icons not visible after compilation - java

ok i am a new one here and tried to write an awesome program:
package f;
import javax.swing.*;
public class dasMain {
public static void main(String[] args) {
ImageIcon img = new ImageIcon("pics/daFaq.png");
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
the thing is that if I run the program from Intellij Idea, then everything works fine, but after compilation the picture disappears
here are the source files of the project:
https://i.ibb.co/Njc8jYp/screen.png
i want to run this awesome code with pictures on other computers, but i only know this way and it doesn't work :(

You probably do not know where your program expects the picture to be. If you modify your code slightly, this information would be evident. Make use of
ImageIcon(URL)
File.toURI()
URI.toURL()
With that your code can look like this:
package f;
import javax.swing.*;
import java.io.File;
public class dasMain {
public static void main(String[] args) {
File png = new File("pics/daFaq.png");
System.out.println("Loading image from " + png.getAbsolutePath());
ImageIcon img = new ImageIcon(png.toURI().toURL());
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
Also I am pretty sure you intend to ship the png together with your code, so you better load it as a resource from the classpath. Here is an example.
I also investigated a bit why you would not see any error message or exception. This is documented in ImageIcon. So you might want to verify the image was loaded using getImageLoadStatus().

If you access the resource with the path like pics/file_name.png, then the pics - is the package name. And it must be located in the directory, marked as resource type. For example, create the directory, named resources in your project root, mark this directory as resource type, and move the pics there:
P. S. I would advise to use Maven or Gradle build system for managing project builds. As it is commonly accepted build management systems for the JVM projects. IDE New Project Wizard has the option to create Maven or Gradle based projects.

Related

How to load video in OpenCV (Java)

I'm trying to load a video file in OpenCV Java, and have narrowed down my issue to the following code:
import org.opencv.core.Core;
import org.opencv.videoio.VideoCapture;
public class OpenCVTest {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.loadLibrary("opencv_videoio_ffmpeg455_64");
VideoCapture capture = new VideoCapture("myVideoFile.avi");
System.out.println(capture.isOpened());
}
}
Of course, this always prints out "false". Accessing my computer's camera with new VideoCapture(0) works fine. After scouring the internet, I'm thoroughly confused as to why loading a video won't work. I followed guides that suggested I needed to add "opencv_videoio_ffmpeg455_64.dll" to my path variable and call System.loadLibrary. I'm new to this, and to be honest, I don't understand what loadLibrary does, or what could be wrong with my setup and code. Any ideas? Thanks in advance.
Here is the answer from similar problem
load the ffmpeg library System.loadLibrary("opencv_ffmpeg300_64");
Open the file:
VideoCapture vC = new VideoCapture("res/video.mp4");
Copy opencv_ffmpeg300_64.dll from opencv\build\x64\vc11\bin to
opencv\build\java\x64
Please note that 64 and .dll may differ from an OS to another, those are for Windows x64
As it turns out, I was using the wrong file path. I (wrongly) assumed that new VideoCapture("my file") would search for "my file" in the directory where the compiled .class files are placed, when in fact it searches in the project root directory. There is no need to call System.loadLibrary("opencv_videoio_ffmpeg455_64");

im trying to create a thread that sends and receives a message in java however im unsure on how to solve the error messages that are displayed [duplicate]

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Display an image in java

public void loadStdImage() throws IOException
{
Image image = ImageIO.read(this.getClass().getResource("/Resources/Images/Student/Capture.png")); //Line 350
ImageIcon icon = new ImageIcon(image);
JLabel lblImage = new JLabel(icon);
lblImage.setIcon(icon);
lblImage.setBounds(753, 50, 149, 171);
add(lblImage);
}
I tried many things... but nothing works out. Continuously showing the following run-time error
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at View.Student.loadStdImage(Student.java:350)
Project folder structure is:
edit:
Found the solution. See the change of icon of the resource folder in the following picture and the above image. I added my resource folder to Java Build Path. Right click on your project, go to properties, then select 'Java Build Path', from there add your folder to java build path.
Cheers
enter image description here
welcome to SO. As you are new here, please read this - https://stackoverflow.com/help/mcve
Let me help you with this for now.
I have standard Eclipse project:
and my test class looks like (minimal):
package q34460547;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LoadTest {
public static void main(String[] args) throws IOException {
new LoadTest().loadStdImage();
}
public void loadStdImage() throws IOException {
Image image = ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
}
}
and now, when I used
ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
image is loaded from res so called source folder in Eclipse.
When I used
ImageIO.read(this.getClass().getResource("ScreenShot005.png"));
image s loaded from the folder in which LoadTest.java file is (to be precise it is also compiled to same folder - in Eclipse it's bin).
You can find more info for example here - What is the difference between Class.getResource() and ClassLoader.getResource()?
edit:
The image has to be on classpath (when using Class.getResource), that's why it was not loaded from Resources folder. There are two options, use another version of ImageIO.read() or make your Resources folder a source folder:

Cannot run my own Java Package

I want to learn to write my own packages so I'm not also relient on an IDE, which I feel I have became. The problem is I cannot figure out how to run my own package, or what the proper method is to run your own package.
Here's a resource I used to learn some basics: http://javaworkshop.sourceforge.net/chapter3.html
Here's my current file structure:
Main.java
/src
projectaqua/
GameFrame.java
/classes
projectaqua/
GameFrame.class
I ran the command in the root directory of the project:javac -d ./classes/ ./src/projectaqua/*.java
I originally created a Main file in the /src/projectaqua directory and attempted to run the file. I was given this error:
Main.java:1: error: package projectaqua does not exist
import projectaqua.GameFrame;
I tried running the application in the /classes/projectaqua directory when compiling the Main file with the package, which gave me a class not defined error.
This compiled my package, the problem I'm facing is I don't understand how you are supposed to import your own package to run it, and where would the file to run the package be?
From what I've learned in school, when writing a GUI application we create a class that has a main function in it to instantiate the frame, and that's it's only job. Where would this be in this structure?
Intuitively it seems that file would be outside of the src files, but I feel like that removes the purpose of the src files. I haven't found anything useful on stackoverflow to this topic, if you do or have please point me in that direction.
More source code:
GameFrame Class:
package projectaqua;
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private int WINDOW_HEIGHT = 500;
private int WINDOW_WIDTH = 500;
private String title = "Project Aqua";
private boolean isVisible = true;
public GameFrame()
{
// Basic Window Defaults
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle(this.title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Content Pane junk
// Will be added
setVisible(this.isVisible);
}
}
The Main class
import projectaqua.GameFrame;
public class Main
{
public static void main(String[] args)
{
GameFrame launch = new GameFrame();
}
}
I now see your problem.
In your question you were not clear that you had trouble running v. compiling. Had you posted this error trace it would have been immediately clear to me what your problem is:
unrollme-dev-dan:projectaqua Dan$ java Main
Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: projectaqua/Main)
Also note that had you Googled NoClassDefFoundError would have found this. The moral here is: understand and research your exact error.
Anyway
unrollme-dev-dan:classes java projectaqua/Main
is what you want. Notice the change of directory. I never bothered to understand why, has to do with relationship between package hierarchy and file structure hierarchy.
Java had two choices when designed: Assume the thing you are talking about is in the global package (yuck!) or try to guess what package it is in. It treats any folder below your working directory as packages. So even though it found a Main class in the directory from which you were running it did not find a Main class in the namespace corresponding to the directory . i.e. the global one.
When you run from one directory up and tell it to run something in projectaqua/ it is now looking for classes starting with projectaqua.
Alternately if you run
unrollme-dev-dan:projectaqua java projectaqua.Main
It looks for the right thing.
try this command at the root of your project
javac -cp ./classes -d ./classes ./src/projectaqua/*.java
Also make sure both your Main.java and GameFrame.java has package projectaqua; at the beginning

Accessing Data inside of a .jar

I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar.
I found the getClass().getClassLoader().getResourceAsStream() method online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well..
I`d be very thankful for any help.
Edit:
Here is a picture of how the directory is organized:
My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it.
Here is the inside of the jar:
again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out.
A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files.
If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it.
For instance, say your package structure looked like this:
So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so:
package codePackage;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ClassUsesResources {
private JLabel label = new JLabel();
public ClassUsesResources() {
try {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
"images/img001s.jpg"));
ImageIcon icon = new ImageIcon(img);
label.setIcon(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
new ClassUsesResources();
}
}

Categories

Resources