How do I load an external jar file in a Applet? - java

So I am working on a project in C# but in order for me to progress I need to get my jar file to run.
This is the jar file
The jar file is a game called Runescape and if I were to double click that jar file it won't do much so I was looking at this example
Applet applet = (Applet)classLoader.loadClass("client").newInstance();
applet.setStub(stub);
applet.setSize(new Dimension(763, 504));
applet.init();
applet.start();
i.add(applet);
i.pack();
i.setDefaultCloseOperation(3);
label.setVisible(false);
Which by the looks of it takes the jar file and runs it in a Applet to give the user a visual representation of the game.
And thought it could be of help.
Now since I am a C# developer with minor Java experience I find it hard to know where to start, I have IntelliJ installed and ready to create a project but what do I need to do in order to get that jar file to run in a Applet so I can later on compile that project and use it a "client" for the game?

Running an applet from an Application is actually not that easy (and not partucally recommended).
I wrote a litte test for your jar file and run into an issue which I belive is that I am missing a proper AppletStub
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
class appletrunner
{
public static void main(String[] args) throws Exception //This is not proper Exception handling!
{
JFrame frame = new JFrame("test");
File jar = new File("gamepack_8614663.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[] {jar.toURI().toURL()}, appletrunner.class.getClassLoader());
Class<?> client = classLoader.loadClass("client");
Applet applet = (Applet)client.newInstance();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
applet.stop();
applet.destroy();
}
});
frame.getContentPane().add(applet);
frame.pack();
frame.setVisible(true);
applet.init(); // Exception here
applet.start();
}
}
This Fails on applet.init() with a cryptic Exception (caused by the obfuscator used by runescape jar). But I think with a proper AppletStub which itself requires a AppletContext it could work.
You could try implementing a class for these interfaces and add them to the applet with addStub(). Hope this is somewhat helpfull.

Related

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.

Why am I getting ClassNotFoundExpection when I have properly imported said class and am looking at it in its directory?

This is my Javac compiling statement:
javac -cp
"C:\java\code\j3D\j3dcore.jar;C:\java\code\j3D\j3dutils.jar;C:\java\code\j3D\vecmath.jar"
Simple.java
compiles with no problems.
The three jar files (j3dcore, j3dutils, and vecmath) are the essential jar's for my program (or at least I am led to believe according to this official tutorial on J3D
For the record I ripped this code almost line from line from the above pdf file.
jar files are correctly located in referenced locations
When I run my Simple program, (java Simple) I am greeted with
Exception in thread "main" java.lang.NoClassDefFoundError:
javax/media/j3d/Cavas3d Caused by: java.lang.ClassNotFoundExpection:
javax.media.j3d.Canvas3D
Currently I am staring directly at this Canvas3D.class that is located within j3dcore.jar\javax\media\j3d\
wtfisthis.jpg
Here is the source code:
//First java3D Program
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.ColorCube;
import javax.media.j3d.*;
import javax.vecmath.*;
import java.awt.GraphicsConfiguration;
public class Simple extends Applet {
public Simple() {
setLayout(new BorderLayout());
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(config);
add("Center", canvas3D);
BranchGroup scene = createSceneGraph();
scene.compile();
// SimpleUniverse is a Convenience Utility class
SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
// This moves the ViewPlatform back a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTransform();
simpleU.addBranchGraph(scene);
} // end of HelloJava3Da (constructor)
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
// Create a simple shape leaf node, add it to the scene graph.
// ColorCube is a Convenience Utility class
objRoot.addChild(new ColorCube(0.4));
return objRoot;
}
public static void main(String args[]){
Simple world = new Simple();
}
}
Did I import correctly?
Did I incorrectly reference my jar files in my Javac statement?
If I clearly see Canvas3D within its correct directory why cant java find it?
The first folder in both j3dcore.jar and vecmath.jar is "javax". Is the compiler getting confused?
If the compiler is getting confused how do I specify where to find that exact class when referencing it
within my source code?
try:
java -cp "C:\java\code\j3D\j3dcore.jar;C:\java\code\j3D\j3dutils.jar;C:\java\code\j3D\vecmath.jar" Simple
you need to include the classpath on the javacommandline as well.
Just doing java simple wont help. You need to put all those jars in classpath while you run the program. Just like you did to compile it.
java -cp C:\java\code\j3D\j3dcore.jar;C:\java\code\j3D\j3dutils.jar;C:\java\code\j3D\vecmath.jar Simple
Please Check Setting the class path

jar could not find main class, despite manifest

I am attempting to put my Java applet into a .Jar so I can sign it, as currently it works locally but throws access denied exceptions when I attempt to run it remotely (it reads other files in the directory).
I created the manifest file correctly when creating the jar and checked it:
Manifest-Version: 1.0
Created-By: 1.6.0_25 (Sun Microsystems Inc.)
Main-Class: netApp
netApp was an applet and runs fine, and it does contain a main method:
import java.awt.*;
import jv.geom.PgElementSet;
import jv.object.PsMainFrame;
import jv.project.PvDisplayIf;
import jv.viewer.PvViewer;
import jv.loader.PgJvxLoader;
import jv.project.PgJvxSrc;
import jv.project.PjProject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import jv.loader.PjImportModel;
import jv.project.PjProject;
import jv.project.PgGeometry;
import jv.viewer.PvViewer;
import jv.object.PsDebug;
import java.applet.Applet;
public class netApp extends Applet {
public Frame m_frame = null;
protected PvViewer m_viewer;
protected PgGeometry m_geom;
protected netAppProj myModel;
public void init() {
// Create viewer for viewing 3d geometries. References to the applet and frame
// allow JavaView to decide whether program runs as applet or standalone application,
// and, in the later case, it allows to use the frame as parent frame.
m_viewer = new PvViewer(this, m_frame);
//myModel.addActionListener();
// Create and load a project which contains the user application. Putting code
// in a JavaView project allows to reuse the project in other applications.
myModel = new netAppProj();
m_viewer.addProject(myModel);
//myModel.start();
m_viewer.selectProject(myModel);
setLayout(new BorderLayout());
// Get 3d display from viewer and add it to applet
add((Component)m_viewer.getDisplay(), BorderLayout.CENTER);
add(m_viewer.getPanel(PvViewer.PROJECT), BorderLayout.EAST);
m_viewer.showPanel(PvViewer.MATERIAL);
// Get default display from viewer
PvDisplayIf disp = m_viewer.getDisplay();
// Register geometry in display, and make it active.
// For more advanced applications it is advisable to create a separate project
// and register geometries in the project via project.addGeometry(geom) calls.
disp.addGeometry(m_geom);
disp.selectGeometry(m_geom);
//disp.addPickListener(myModel);
/*until here */
}
/**
* Standalone application support. The main() method acts as the applet's
* entry point when it is run as a standalone application. It is ignored
* if the applet is run from within an HTML page.
*/
public static void main(String args[]) {
netApp app = new netApp();
// Create toplevel window of application containing the applet
Frame frame = new jv.object.PsMainFrame(app, args);
frame.pack();
// Store the variable frame inside the applet to indicate
// that this applet runs as application.
app.m_frame = frame;
app.init();
// In application mode, explicitly call the applet.start() method.
app.start();
// Set size of frame when running as application.
netAppProj myModel = new netAppProj();
frame.setSize(640, 550); frame.setBounds(new Rectangle(420, 5, 640, 550));
frame.setVisible(true);
}
/** Print info while initializing applet and viewer. */
public void paint(Graphics g) {
g.setColor(Color.blue);
//g.drawString("Loading Geometry Viewer Version: "+PsConfig.getVersion(), 20, 40);
g.drawString("Loading Projects .....", 20, 60);
}
/**
* Does clean-up when applet is destroyed by the browser.
* Here we just close and dispose all our control windows.
*/
public void destroy() { m_viewer.destroy(); }
/** Start viewer, e.g. start animation if requested */
public void start() { m_viewer.start(); }
/** Stop viewer, e.g. stop animation if requested */
public void stop() { m_viewer.stop(); }
}
I have tried everything when creating the jar including just doing a:
jar cfm app.jar Manifest.txt *.*
When I try and run the jar from windows explorer or by running:
java -jar app.jar
it fails. with the generic error:
Could not find the main class: netApp. Program will exit.
netApp.class is definitely in the Jar.
Thanks in advance for your help.
Given the error message, it looks like it´s got the manifest correctly, but not the class itself. Run jar tvf app.jar to have a look.
Your jar command looks a little off to me... shouldn´t it be
jar cfm app.jar manifest.txt *.*
?

How do relative file paths work in Eclipse?

So my 2009 new years resolution is to learn Java. I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse. Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from.
Here is the sample code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridLayout;
class TeamFrame extends JFrame {
public TeamFrame() throws IOException {
PlayerPlus player;
Scanner myScanner = new Scanner(new File("Hankees.txt"));
for (int num = 1; num <= 9; num++) {
player = new PlayerPlus(myScanner.nextLine(), myScanner.nextDouble());
myScanner.nextLine();
addPlayerInfo(player);
}
add(new JLabel());
add(new JLabel(" ------"));
add(new JLabel("Team Batting Aberage:"));
add(new JLabel(PlayerPlus.findTeamAverageString()));
setTitle("The Hankees");
setLayout(new GridLayout(11,2));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
void addPlayerInfo(PlayerPlus player) {
add(new JLabel(player.getName()));
add(new JLabel(player.getAverageString()));
}
}
And you can see in the below screen shot I have included this file.
image no longer available
Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files.
Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\ drive the program compiles and runs fine.
Scanner myScanner = new Scanner(new File("C:\\Hankees.txt"));
So basically, my question is what am I doing wrong? Or is Eclipse responsible for this in some way?
Thanks for any and all help!
You need "src/Hankees.txt"
Your file is in the source folder which is not counted as the working directory.\
Or you can move the file up to the root directory of your project and just use "Hankees.txt"
A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.
New run configurations default to using the project directory for the working directory, though this can also be changed.
This code shows the difference between the working directory, and the location of where the class was loaded from:
public class TellMeMyWorkingDirectory {
public static void main(String[] args) {
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
}
}
The output is likely to be something like:
C:\your\project\directory
/C:/your/project/directory/bin/
This is really similar to another question.
How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.
...just thought I'd add some extra info. I'm new here! I'd like to help.
You can always get your runtime path by using:
String path = new File(".").getCanonicalPath();
This provides valuable information about where to put files and resources.
Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:
The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.
Eclipse sets the working directory to the top-level project folder.

Categories