How to resolve the following errors (about jmathpolt)? - java

I want to use packages such as jmathplot to draw function images, but after adding related packages, a problem that I can't solve is thrown.
import javax.swing.*;
import org.math.plot.*;
public class Example {
public static void main(String[] args) {
// define your data
double[] x = { 1, 2, 3, 4, 5, 6 };
double[] y = { 45, 89, 6, 32, 63, 12 };
// create your PlotPanel (you can use it as a JPanel)
Plot2DPanel plot = new Plot2DPanel();
// define the legend position
plot.addLegend("SOUTH");
// add a line plot to the PlotPanel
plot.addLinePlot("my plot", x, y);
// put the PlotPanel in a JFrame like a JPanel
JFrame frame = new JFrame("a plot panel");
frame.setSize(600, 600);
frame.setContentPane(plot);
frame.setVisible(true);
}
}
And the relevant jar files are downloaded on GitHub.

You are apparently using the 1.0 version of the JMathPlot library (either from GitHub or from Maven Central). That version of the JAR is missing the /org/math/plot/icons/ folder that contains the library's standard icons. That is leading to an NPE when Swing attempts to load an icon from the classpath.
The solution is to use the JMathPlot 1.0.1 JAR which has the missing icons. You can download in by hand from Maven Central via this URL:
https://search.maven.org/artifact/com.github.yannrichet/JMathPlot/1.0.1/jar
If you use Maven, Gradle and so on for your Java builds, the correct Maven dependency is
<dependency>
<groupId>com.github.yannrichet</groupId>
<artifactId>JMathPlot</artifactId>
<version>1.0.1</version>
</dependency>
Alternatively, you could get a working JAR by building the library from source.
It is a shame that the repo owner has not uploaded the 1.0.1 JAR file to GitHub ... leaving the broken 1.0 version as a trap for people to fall into.

Related

Java Library Commons Lang3 'ClassNotFoundException' error

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class MonsterGame {
public static void main(String[] args)
{
Monster.buildBattleBoard();
char[][] tempBattleBoard = new char[10][10];
// ObjectName[] ArrayName = new ObjectName[4];
Monster[] Monsters = new Monster[4];
// Monster(int health, int attack, int movement, String name)
Monsters[0] = new Monster(1000, 20, 1, "Frank");
Monsters[1] = new Monster(500, 40, 2, "Drac");
Monsters[2] = new Monster(1000, 20, 1, "Paul");
Monsters[3] = new Monster(1000, 20, 1, "George");
Monster.redrawBoard();
for (Monster m : Monsters) {
if(m.getAlive()) {
int arrayItemIndex = ArrayUtils.indexOf(Monsters, m);
m.moveMonster(Monsters, arrayItemIndex);
}
}
Monster.redrawBoard();
}
}
When trying to run this code, I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/ArrayUtils
at MonsterGame.main(MonsterGame.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.ArrayUtils
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 1 more
I have two files, in the same package. I've only shown this one because I do not believe the other file is the problem.
I followed a tutorial on how to use java libraries: download, import, build path etc.
The problem here is, the import seems to be fine but actually using the library is the problem.
I'm very new to Java so sorry if this is a very simple error to fix.
Thank you for any response/feedback in advance.
The referenced library you are using (apache common lang3) and any other library for that matter is used in three different ways.
First, you need the library during development, so your IDE can
validate your code, when you call classes, objects and methods from
the library.
During compilation you need the library, so the java
compiler can reference the right paths, and optimize your code,
where possible.
You need the library during runtime, when your program is run by the Java Virtual Machine, so it can find whatever you used from the library.
The first 2 are usually seen as one, because both is usually considered 'compile time', though strictly speaking only the second one actually is. This means that you need to have the library in place for the IDE (for points 1 and 2) and for the program (point 3). Your exception is thrown, because during runtime, your library is not found by the ClassLoader. The ClassLoader is the way the JVM loads classes for the programs it uses. If the JVM does not find a class, it cannot continue to execute the Thread you are running, and you are probably only running one Thread (a main thread).
Therefore your program breaks, and stops running. Please either recheck the tutorial you are using on how to correctly import libraries or export the library to the lib folder next to the jar you are exporting.
Edit: When using an up to date version of eclipse, and exporting a project as runnable jar, you are asked what way you want to handle libraries:
If you do not see this subsection of the export dialog, you are doing something wrong (probably you are not exporting as runnable jar).

VLCJ cant find plugins in normal installation

My VLC.exe works fine with a bit of lag. But my simple VLCJ code does not work.
import javax.swing.JPanel;
import com.sun.jna.NativeLibrary;
import javax.swing.JFrame;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
public class VideoPanel extends JPanel {
private static final String NATIVE_LIBRARY_SEARCH_PATH = "C:/Program Files/VideoLAN/VLC";
private EmbeddedMediaPlayerComponent mediaPlayerComponent;
public VideoPanel() {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), NATIVE_LIBRARY_SEARCH_PATH);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
this.add(mediaPlayerComponent);
}
public static void main(String args[]){
JFrame frame = new JFrame();
frame.add(new VideoPanel());
frame.setBounds(100, 100, 800, 450);
frame.setVisible(true);
}
}
I am using 64bit java 1.8.0_60. And I am using vlc 2.2.4 64bit on Windows 10 64bit.
My error message was this.
[00000000018bbbb0] core libvlc error: No plugins found! Check your VLC installation.
Exception in thread "main" java.lang.RuntimeException: Failed to initialise libvlc.
This is most often caused either by an invalid vlc option being passed when creating a MediaPlayerFactory or by libvlc being unable to locate the required plugins.
If libvlc is unable to locate the required plugins the instructions below may help:
In the text below represents the name of the directory containing "libvlc.dll" and "libvlccore.dll" and represents the name of the directory containing the vlc plugins...
For libvlc to function correctly the vlc plugins must be available, there are a number of different ways to achieve this:
1. Make sure the plugins are installed in the "/plugins" directory, this should be the case with a normal vlc installation.
2. Set the VLC_PLUGIN_PATH operating system environment variable to point to "".
More information may be available in the log.
at uk.co.caprica.vlcj.player.MediaPlayerFactory.(MediaPlayerFactory.java:300)
at uk.co.caprica.vlcj.player.MediaPlayerFactory.(MediaPlayerFactory.java:259)
at uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent.onGetMediaPlayerFactory(EmbeddedMediaPlayerComponent.java:349)
at uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent.(EmbeddedMediaPlayerComponent.java:217)
at VideoPanel.(VideoPanel.java:19)
at VideoPanel.main(VideoPanel.java:31)
What should I do?
This is a not uncommon problem, especially it seems on Windows platforms.
The vlcj introduction tutorial uses this code to find the native library and its plugins:
package tutorial;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class Tutorial {
public static void main(String[] args) {
boolean found = new NativeDiscovery().discover();
System.out.println(found);
System.out.println(LibVlc.INSTANCE.libvlc_get_version());
}
}
This NativeDiscovery class encapsulates everything needed, including setting the VLC_PLUGIN_PATH environment variable, for the most common cases.
This is the recommended way to make sure LibVLC gets properly initialised with vlcj, so please try it.

Java Swing window not appearing in Eclipse

I have this code below to display a window using Java Swing. The problem is when I run the code in eclipse the window does not show. When I export the file as an executable JAR file and run it it works. Is there a bug with eclipse that prevents it from running it from there?
What am I missing?
package com.gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
public class Calculator {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Calculator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
//frame.setBounds(100, 100, 450, 300);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("Hello World");
frame.getContentPane().add(lblNewLabel, BorderLayout.NORTH);
}
}
Some projects created by Eclipse/WindowBuilder in macOS have this window-not-showing-up problem.
When an app is created through New > Project > WindowBuilder > SWT Designer > SWT/JFace Java Project, the new project automatically includes several extra jar files in classpath. Certain jar file(s) trigger eclipse to use special arguments (-XstartOnFirstThread) in the command (ps aux | grep to find out) when starting the application, and startOnFirstThread is giving us the problem here. AFAIK, -XstartOnFirstThread is added only in MacOS.
Solution 1: don’t use “WindowBuilder > SWT Designer > SWT/JFace Java Project” to create the project. You can just create a regular java project, and add the stuff you need.
Solution 2: remove the jar files. Right click on project > Properties > Build Path > Configure Build Path > Libraries, remove org.eclipse.swt (removing this one suffices in my case, there might be others in your case).
I had the same problem, and this is what worked for me (after the help of some folks on stackoverflow).
It turns out I had a library problem. I had had imported all the jars in the .lib directory from jfreechart. In reality only two were needed and some unnecessary ones were labeled swt and experimental. Once I removed all the ones that were not needed, did a clean, and rebuilt, everything worked fine.
Oddly, changing the order of the jfreechart library (which included the conflicting jars) to the bottom did not help, the extra jars had to be removed.
Not a jfreechart issue, obviously my own library import issue. So I suggest you try to remove some of the libraries that may be conflicting, then clean, build, and run again. Good luck.
Had the same issue and the root cause turned out to be the extra .jar in the build path(using macOS). For me, it worked after removing the org.eclipse.swt.cocoa.macosx.x86_64_3*.jar too. part.

JFreeChart Null Pointer issue

I'm just trying to run a demo of a 'simple' pie chart I found online. I'm running this in Eclipse Kepler and I keep getting,
Exception in thread "main" java.lang.NullPointerException
at org.apache.fontbox.afm.AFMParser.main(AFMParser.java:304)
when I try to run the program. I would think, considering where I got the code (linked off of a JChart site), that it would run without issue. Just trying to see if anyone can see something I can't.
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class BarChartDemo {
public static void main(String[] args){
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Category 1", 50.0);
dataset.setValue("Category 2", 50.0);
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
dataset,
true,
true,
false
);
ChartFrame frame = new ChartFrame("First",chart);
frame.pack();
frame.setVisible(true);
}
}
I was able to get the chart to appear without changing your code. Did you include both jars (jfreechart, jcommons) in your build path?
After some battling and researching (guessing), I came across this class via some Adobe Font Metrics googling. Incidentally I can't remember exactly where I found it, but it solved my issue. I'll spare the SO servers and not post the 1000(+)-line code, but here it is as a gist if anyone has the same problem. I just included it in my project source file as a separate class, and voila...
I'm still not sure why my project wouldn't run without this. It worked on other systems, but not my Eclipse Kepler (Mac OS 10.9). If anyone can tell me exactly why it kept failing, I'd be very thankful.

Attempting to set JLabel icon to image directory, null pointer exception instead

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.(ImageIcon.java:205)
JLabel background = new JLabel(new ImageIcon(getClass().getResource("/resources/splashscreen.jpeg")));
The above line is the exact line throwing the exception, and it makes me believe that the location of the file is not correct, but I have tried numerous things but to no success.
The folder structure seems to be correct, the image is within the resources folder which is within the project folder, and the folder(with the image) is next to the src folder not within. This application has to have the ability of being used offline otherwise I would just use the URL. Is there a known bug with this in the Eclipse IDE?
Figured it out. It seems that I was putting the file in the wrong location, putting it with the .class files solved the problem. Not sure if this was a proper solution or just a work around unfortunately. I had to go back to the basics .java files are compiled and the .class files are actually running, and I need to backtrack from the current working directory.
try this,put your image in an external folder outside source folder called Images
and after try:
public class Test{
public Test()
{
JFrame frame= new JFrame();
JLabel label = new JLabel(new ImageIcon("Images/image.jpeg"));
frame.getContentPane().add(label);
Container log = login.getContentPane();
log.setBackground(Color.WHITE);
frame.setVisible(true);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args)
{
new Test();
}
try to launch this app.
Actually, you have to put "resource" folder into source folder in this case.
Seems like "/resources/splashscreen.jpeg" is an absolute path. Try without the leading slash or give the "real" absolute path.
Edit: I'm pretty sure the file is not found and getResource() returns null.
Why not try to get the file size? Fiddle around with this:
File f = new File("/resources/splashscreen.jpeg");
long length = f.length();
until length != 0
:-)
I just fiddled with the same problem and #OiRC answer helped me ALOT. I followed youtube tutorials to get code as follows:
ImageIcon helpIcon = new ImageIcon(getClass().getResource("helpIcon.png"));
lbl_helpIcon = new JLabel(new ImageIcon("helpIcon.png"));
lbl_helpIcon.setBounds(178, 11, 139, 62);
lbl_helpIcon.setIcon(helpIcon);
I kept getting a NullPointerException on
ImageIcon helpIcon = new ImageIcon(getClass().getResource("helpIcon.png"));
Until I tried this
lbl_helpIcon = new JLabel(new ImageIcon("helpIcon.png"));
lbl_helpIcon.setBounds(178, 11, 139, 62);
Worked like a charm! btw I stored my icon image like so

Categories