I developer a basic Processing PApplet to run as a Tool in the Arduino IDE and that ran fine until Arduino 1.5.8. The problem I have is that in Arduino 1.6.0 some of the code got refactored and this happened on the Arduino side:
" In order to provide a better command line, IDE has been refactored
into app and arduino-core which is the old core In order to avoid
conflicts between classes, PApplet was moved from
processing.core.PApplet to processing.app.legacy.PApplet "
This explanation came from one of the Arduino IDE developers. It's worth noting that processing.app.legacy.PApplet is a (very)stripped down version of PApplet, discarding all graphics capabilities which I need.
Initially I was getting this error:
Uncaught exception in main method: java.lang.NoClassDefFoundError: processing/core/PApplet
Placing Processing's core.jar in the same location as the eclipse exported tool jar fixed this issues, but let to another:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: You need to use "Import Library" to add processing.core.PGraphicsJava2D to your sketch.
at processing.core.PApplet.makeGraphics(Unknown Source)
at processing.core.PApplet.init(Unknown Source)
The part that is confusing is I've used Processing's library source java files instead of the core.jar compiled library to avoid this issue, but it didn't change anything.
I've gone through PApplet's source code and found the graphics/renderer class gets loaded and instantiated at runtime here like so:
Class<?> rendererClass =
Thread.currentThread().getContextClassLoader().loadClass(renderer);
Constructor<?> constructor = rendererClass.getConstructor(new Class[] { });
PGraphics pg = (PGraphics) constructor.newInstance();
and this is where the ClassNotFoundException is caught throwing the Runtime exception:
catch (ClassNotFoundException cnfe) {
// if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) {
// throw new RuntimeException(openglError +
// " (The library .jar file is missing.)");
// } else {
if (external) {
throw new RuntimeException("You need to use \"Import Library\" " +
"to add " + renderer + " to your sketch.");
} else {
throw new RuntimeException("The " + renderer +
" renderer is not in the class path.");
}
}
I'm getting more comfortable with java, but I don't have enough experience to figure this one out. It looks like a classpath issue, but I'm not sure why this happens and how I should tell java where to find the classes it needs to load.
Here is the code test I'm using based on the Arduino Tool sample that comes with the IDE. Currently I'm exporting the jar file (not runnable) from eclipse:
/*
Part of the Processing project - http://processing.org
Copyright (c) 2008 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.transformers.supermangletron;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import processing.core.PApplet;
import processing.app.Editor;
import processing.app.tools.Tool;
//import processing.app.legacy.PApplet;
/**
* Example Tools menu entry.
*/
public class Mangler implements Tool {
private Editor editor;
public void init(Editor editor) {
this.editor = editor;
}
private void setupSketch(){
int w = 255;
int h = 255;
// PApplet ui = new PApplet();
TestApp ui = new TestApp();
JFrame window = new JFrame(getMenuTitle());
window.setPreferredSize(new Dimension(w,h+20));
window.add(ui);
window.invalidate();
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.init();
System.out.println("setup complete");
}
public String getMenuTitle() {
return "Mangle Selection";
}
public void run() {
setupSketch();
}
}
and here's the basic test Applet I'm trying to display:
package com.transformers.supermangletron;
import processing.core.PApplet;
public class TestApp extends PApplet {
public void setup(){
size(100,100);
}
public void draw(){
background((1.0f+sin(frameCount * .01f)) * 127);
}
}
How can I fix this ClassNotFoundException with my setup?
Any hints on what I should double check regarding class paths?
If you're getting this error when you run from eclipse, you have to add the library jars to your classpath. You do this by right-clicking your project, going to properties, then to Java Build Path. Make sure the library jars are listed under the Libraries tab.
If you're getting this error when you run an exported jar, then you need to do one of two things:
Either make sure you export a runnable jar with the library jars embedded inside the main jar. Do this from eclipse by right-clicking the project, going to Export, then choosing "runnable jar" from the list.
Or, make sure you set the classpath as a JVM argument. You do this using the -cp option from the command line.
Related
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.
I'm trying to teach myself java syntax and using minecraft as a platform for diving in. I'm having a problem though because none of my textures are being loaded. For that matter neither are my localizations. Here is the code for my block
package net.richbaird.testtutorial.blocks;
import cpw.mods.fml.common.registry.GameRegistry;
//import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.richbaird.testtutorial.lib.constants;
public class OrangeBlock extends Block {
private String blockName = "orangeBlock";
public OrangeBlock() {
super(Material.rock);
this.setBlockName(constants.MODID + "_" + blockName);
this.setCreativeTab(CreativeTabs.tabBlock);
GameRegistry.registerBlock(this,blockName);
this.setBlockTextureName(constants.MODID + ":" + blockName);
//LanguageRegistry.addName(this,"tutorial block");
}
}
here is my constants class
package net.richbaird.testtutorial.lib;
public class constants {
public static final String MODID = "testtutorial";
public static final String MODNAME = "Test Tutorial";
public static final String VERSION = "1.0";
}
I have my texture saved at
~/IdeaProjects/testmod/src/main/resources/assets/testtutorial/textures/blocks/orangeBlock.png
According to the log it is unable to find my texture. Here's the message I'm getting
[08:08:14] [Client thread/ERROR]:
Using missing texture, unable to load
testtutorial:textures/blocks/orangeBlock.png
java.io.FileNotFoundException: testtutorial:textures/blocks/orangeBlock.png
The client loads and my item shows up but with a default black and purple texture. What have I done wrong? I'm thinking it might have to do with my naming conventions, since the .lang file never gets read either, and the only way I can give my block a friendly name is with the now depreciated LanguageRegistry.addName() method
For those who are curious, it's a bug with intellij 14 looks like. Adding this line to the bottom of the build.gradle that comes with forge
sourceSets {
main { output.resourcesDir = output.classesDir }
}
And running gradle setupDecompWorkspace idea --refresh-dependencies
fixed the problem.
I recently ran into this bug after updating IntelliJ, and while richbai90's solution did fix the immediate issue, it also broke compiling the mod into a jar (the assets folder gets included twice). After some digging around, I eventually found the root of the issue: IntelliJ was delegating the build task to Gradle, which put the assets and classes in separate folders, and Forge didn't know they belong to the same mod. The solution that worked for me was to build and run using the IDE, which is in the Settings dialog under Build, Execution, Deployment | Build Tools | Gradle (the help page has more detailed instructions). On older versions of IntelliJ, this was called "Delegate IDE build/run actions to gradle" (see the help page).
Running into some problems making a piece of code run on my mac.
Had someone write me an image analysis java app but I keep getting this error when trying to run it on netbeans.
run: Exception in thread "main" java.lang.UnsatisfiedLinkError: no
opencv_java249 in java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857) at
java.lang.Runtime.loadLibrary0(Runtime.java:870) at
java.lang.System.loadLibrary(System.java:1119) at
image.prossing.Test.main(Test.java:28) Java Result: 1 BUILD SUCCESSFUL
(total time: 0 seconds)
Have the netbeans project, and added the necessary jar files as libraries. The programmer told me to download the correct OpenCV version and copy the opencv.dll file to my java/jre/bin folder. But I cannot find the dll file or the java/jre folder.
I know most programming happens on windows for a reason. Hope someone can help me resolve this issue and run this application on my mac.
Here is the first part of the code, the part that is most probably creating the error:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package image.prossing;
/**
*
* #author Dumith Salinda
*/
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import static org.opencv.core.Core.FONT_HERSHEY_SIMPLEX;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
public class Test {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Sorry if it's not that clear, let me know what info to add if something is missing or not clear.
Would truly appreciate any help you could give. Sincerely
Meir Warcel
Look into your OpenCV directory;
For an example this; (installed using brew install opencv3 --with-java --with-python3)
/usr/local/Cellar/opencv3/XXX/share/OpenCV/java
You will see;
libopencv_javaXXX.so opencv-XXX.jar
Now that you already have OpenCV's native library for Java (libopencv_javaXXX.so) compiled with you, the only thing left is, mac's dynamic library.
Link libopencv_javaXXX.so to libopencv_javaXXX.dylib;
ln -s libopencv_javaXXX.so libopencv_javaXXX.dylib
Now add /usr/local/Cellar/opencv3/XXX/share/OpenCV/java as Native Library Locations in IntelliJ or something similar in Eclipse.
Or add this to your JVM arguments;
-Djava.library.path=/usr/local/Cellar/opencv3/XXX/share/OpenCV/java
On a mac running OSX Yosemite, I dropped the libopencv_java2412.dylib file into /Library/Java/Extensions and it worked.
After you build opencv, the libopencv_java2412.dylib is generated in /build/lib.
After Spending a lots of time , and using different suggestions from StackOverflow I managed to get solution for windows. but I am adding a solution for mac as well. hope it should work.
Load your lib as per your system configuration.
private static void loadLibraries() {
try {
InputStream in = null;
File fileOut = null;
String osName = System.getProperty("os.name");
String opencvpath = System.getProperty("user.dir");
if(osName.startsWith("Windows")) {
int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model"));
if(bitness == 32) {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
else if (bitness == 64) {
opencvpath=opencvpath+"\\opencv\\x64\\";
} else {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
}
else if(osName.equals("Mac OS X")){
opencvpath = opencvpath+"Your path to .dylib";
}
System.out.println(opencvpath);
System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
} catch (Exception e) {
throw new RuntimeException("Failed to load opencv native library", e);
}
}
2.now use this method as per your need
public static void main(String[] args) {
loadLibraries();
}
Building on Harsh Vakharia's answer i tried installing OpenCV on my mac with macports:
sudo port install opencv +java
ls /opt/local/share/OpenCV/java
libopencv_java343.dylib opencv-343.jar
To use this library I was hoping to be able to modify the library path at runtime which was discussed in
Adding new paths for native libraries at runtime in Java
And ended up with the following helper class and unit test. The code is now part of the
Self Driving RC-Car open Source project in which I am a comitter.
JUnit Test
/**
* #see <a href=
* 'https://stackoverflow.com/questions/27088934/unsatisfiedlinkerror-no-opencv-java249-in-java-library-path/35112123#35112123'>OpenCV
* native libraries</a>
* #throws Exception
*/
#Test
public void testNativeLibrary() throws Exception {
if (debug)
System.out.println(String.format("trying to load native library %s",
Core.NATIVE_LIBRARY_NAME));
assertTrue(NativeLibrary.getNativeLibPath().isDirectory());
assertTrue(NativeLibrary.getNativeLib().isFile());
NativeLibrary.load();
}
NativeLibrary
package com.bitplan.opencv;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
import org.opencv.core.Core;
/**
* load OpenCV NativeLibrary properly
*/
public class NativeLibrary {
protected static File nativeLibPath = new File("../lib");
/**
* get the native library path
*
* #return the file for the native library
*/
public static File getNativeLibPath() {
return nativeLibPath;
}
/**
* set the native library path
*
* #param pNativeLibPath
* - the library path to use
*/
public static void setNativeLibPath(File pNativeLibPath) {
nativeLibPath = pNativeLibPath;
}
/**
* get the current library path
*
* #return the current library path
*/
public static String getCurrentLibraryPath() {
return System.getProperty("java.library.path");
}
/**
* Adds the specified path to the java library path
*
* #param pathToAdd
* the path to add
* #throws Exception
* #see <a href=
* 'https://stackoverflow.com/questions/15409223/adding-new-paths-for-native-libraries-at-runtime-in-java'>Stackoverflow
* question how to add path entry to native library search path at
* runtime</a>
*/
public static void addLibraryPath(String pathToAdd) throws Exception {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
// get array of paths
final String[] paths = (String[]) usrPathsField.get(null);
// check if the path to add is already present
for (String path : paths) {
if (path.equals(pathToAdd)) {
return;
}
}
// add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
public static File getNativeLib() {
File nativeLib = new File(getNativeLibPath(),
"lib" + Core.NATIVE_LIBRARY_NAME + ".dylib");
return nativeLib;
}
/**
* load the native library by adding the proper library path
*
* #throws Exception
* - if reflection access fails (e.g. in Java9/10)
*/
public static void load() throws Exception {
addLibraryPath(getNativeLibPath().getAbsolutePath());
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
}
Exception is occurring from below line of code:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Your program is trying to load a native library by the name of argument in call to loadLibrary method, which it is not able to locate. Make sure that native library (opencv.dll) is placed at one of the locations present in java.library.path system property as JVM looks at these locations for loading any native library (which might not contain 'java/jre/bin').
You can print java.library.path in your program like below:
System.out.println(System.getProperty("java.library.path"));
You cannot just put Windows library (dll file) on Mac and have it running - you need to compile the library for Mac first (or get Mac version of the library).
Please see here for tips on how to do it:
.dll Equivalent on Mac OS X
How do third-party libraries work in Objective-C and Xcode?
How to use a Windows DLL with Java in Mac OS X?
Instead of struggling with manual installation of OpenCV libraries I suggest you use OpenCV Java library packaged by OpenPnP (https://github.com/openpnp/opencv) that includes all required DLL.
It does not require additonal steps except of adding it to your build automation tool configuration (Gradle in my case) and adding the following code to load the library:
System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
Just add into the path the folder where your opencv_java249.dll is; it would be something like C:\bin\opencv\build\java\x32 or C:\bin\opencv\build\java\x64 depending of your machine architecture. The problem is that java.library.path is actually the path variable.
netebans right klick project chosew properti
chose run, working direktory, click Browser change to opencv folder, release/lib,
I am attempting to create an applet to replace my ActiveX control because it recently started having problems even though it has worked for years. All this will do is read data from a serial port, a barcode scanner in my case, and pass the data to an input box. Also any pointers on ways I could make this better would be greatly appreciated.
Code:
package checkin;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import netscape.javascript.*;
import java.applet.Applet;
public class MainSerial extends Applet {
static SerialPort port;
static JSObject window;
public static void main(String[] args) { //WARNING
SerialPort port = new SerialPort("COM1");
try {
port.openPort();
port.setParams(9600, 8, 1, 0);
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;
port.setEventsMask(mask);
port.addEventListener(new SerialPortReader()); //ERROR
} catch (SerialPortException ex) {
window.eval("alert('Could not open port.\nThe port may be in use by another program.')");
}
}
class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()) {
try {
byte buffer[] = port.readBytes();
int x = 0;
int count = buffer.length;
StringBuilder data = new StringBuilder();
while(x < count) {
data.append(buffer[x]);
x++;
}
window.eval("getSerialData('" + data.toString() + "')");
} catch (SerialPortException ex) {
window.eval("alert('Port could not be read.')");
}
}
}
}
}
Error Thrown with Eclipse:
The serializable class MainSerial does not declare a static final serialVersionUID field of type Long
Warning thrown with Eclipse:
No enclosing instance of MainSerial is accessible. Must qualify the allocation with an enclosing instance of type MainSerial.
This is my first attempt at Java, please excuse my ignorance. What doesn't make sense to me is why do I see these errors in Eclipse but not NetBeans? Also, if the line
port.addEventListener(new SerialPortReader());
Is in that specific parent why would I need to reinitialize it? I'm sure I'm missing something small and probably quite obviously but any help is greatly appreciated. The reason I am attempting to create an applet is due to the increasing problems with my ActiveX control.
Eclipse's compiler has a lot of configurable warnings and errors that other compilers may or may not have. In general the default settings are quite reasonable and you should try to fix them if possible. Many can easily be fixed using the Quick Fix feature: right-click on an error in the Markers (or Problems) view and choose Quick Fix....
Alternatively, you can right-click on the underline (yellow or red) in the code where the error or warning is, and choose Quick Fix....
Not every warning/error has a quick fix, but many do.
If you want to disable a particular warning or error, right-click your project and open the Properties dialog. In there, look under Java Compiler > Errors/Warnings to find all of the configurable ones. You'll have to Enable project specific settings unless you want the same settings to apply to all projects in your workspace.
Eclipse typically throws a warning around ServialVersionUID when you create a serializable object without specifying a serial version ID.
having serial version IDs is a best practice, not a strict requirement, and differend IDEs behave differently about it. More info on why you may want it can be found here. Please note: this should be a warning, not an error. If it is a warning, there are three ways of avoiding this:
Ask Eclipse to generate a default ID for you (it will generate private static final long serialVersionUID = 1L;)
Generate one your self
Tell Eclipse to ignore the warning (adding the #SuppressWarnings("serial") annotation)
For the other issue, there is a wide liteerature out there. Here is a link you may want to read.
Hope this helps.
I'm discovering the jni4net. This is the technology used to provide the bridge between Java and .NET. So, I created new Eclipse Java project and copied the sample code from jni4net-0.8.6.0-bin/samples/myCSharpDemoCalc->MyCalcUsageInJava.java into this project. However the code cannot be compiled because two imports "mycsharpdemocalc.DemoCalc" and "mycsharpdemocalc.ICalc" cannot be found. I don't understand how to integrate/import mycsharpdemocalc.c into the Java project so that the code could be compiled.
import net.sf.jni4net.Bridge;
import java.io.IOException;
import mycsharpdemocalc.DemoCalc;
import mycsharpdemocalc.ICalc;
public class MyCalcUsageInJava {
public static void main(String arsg[]) throws IOException {
Bridge.init();
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("MyCSharpDemoCalc.j4n.dll"));
ICalc calc = new DemoCalc();
final int result = calc.MySuperSmartFunctionIDontHaveInJava("Answer to the Ultimate Question of Life, the Universe, and Everything");
System.out.printf("Answer to the Ultimate Question is : " + result);
}
}
There is ReadMe in each sample directory.
You have to use proxygen tool to generate the proxies (which are used in the java code).
There is generateProxies.cmd batch to do that.
More complex things may need config file for proxygen.
Also there is community Wiki