Error: Could not find or load main class FrameDemo? - java

Here is my code,
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I copied this from the oracle website with copy and paste verbatim. Here
And here is what I am doing in command prompt? What is the problem here. I am seriously at my wiits end.
Directory of C:\Users\headgearxthree\Desktop\SCRAP\JAVA\compile\gui
12/17/2016 12:42 PM <DIR> .
12/17/2016 12:42 PM <DIR> ..
12/17/2016 12:29 PM 2,765 FrameDemo.java
1 File(s) 2,765 bytes
2 Dir(s) 51,945,787,392 bytes free
C:\Users\headgearxthree\Desktop\SCRAP\JAVA\compile\gui>javac Framedemo.java
C:\Users\headgearxthree\Desktop\SCRAP\JAVA\compile\gui>java -cp . FrameDemo
Error: Could not find or load main class FrameDemo
C:\Users\headgearxthree\Desktop\SCRAP\JAVA\compile\gui>
I made a Hello World! program just before in its parent directory with no problems. What is this error? What is going wrong? These examples should be simple and eloquent. This is a simple how to and yet as soon as graphics are involved all programming on windows goes to sh*t. Wtf? This is not a duplicate. All similar questioned reference a specific instance. I have phrased this in a none partisan fashion so it can help the many. Please do not lock.

The class is in package components This means that
its fully qualified name is components.FrameDemo, not FrameDemo.
its source file should be in a directory named components: the structure of directories should match the structure of the packages.
It's also a bad idea to mix source files and class files in the same directory. You should put your sources under an src directory, and classes under a separate classes directory:
mkdir src
mkdir classes
mkdir src/components
mv FrameDemo.java src/components
javac -d classes src/components/FrameDemo.java
java -cp classes components.FrameDemo
Note that, if you has read the tutorial properly and downloaded the whole project zip file from https://docs.oracle.com/javase/tutorial/uiswing/examples/components/, you would have the right structure from the start.

The java file name while compiling is incorrect.
javac Framedemo.java
it Should be
javac FrameDemo.java

Related

How to correctly create and import packages in Java

I am using Netbeans 8.1 and Java 8.
I have a Java program named "MyFrame.java" and I want to create a package with its classes and methods - I call this package "myframe" and it is located at "\Lab\MyFrame\src\myframe". See picture:
(Ignore the red lines - this is a dummy version).
The class file is created after compiling, using the command "javac MyFrame.java", in the same directory \myframe. Now I want to import the package "myframe" in a new Java file "MoreButtons.java". So it would look like this and for convenience I save it in \src:
Compiling and executing MoreButtons.java works fine. The package has been imported. But now MyFrame.java is a bit trickier to execute: the naïve approach yields:
Translation: Error: Could not find or load main class
This seems to be quite a common problem and one of the solutions is simply to add the directory (\myframe) to the PATH environment variable. However, doing this still produced the error.
1) What am I doing wrong and how can I fix this?
2) What is the correct way to create and import custom-made packages in Java?
Make sure that terminal is at path Lab\MyFrame\src:
javac myframe\MyFrame.java MoreButtons.java
java -cp .; myframe.MyFrame
P.S. (/,:=linux/mac) or (\,;=windows)
MyFrame.java
package myframe;
public class MyFrame extends javax.swing.JFrame{
public MyFrame(String title){
super(title);
setSize(200,100);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
MoreButtons.java
public class MoreButtons {
public static void main(String[]args){
new myframe.MyFrame("More Buttons");
}
}

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

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.

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.

How to change the classpath and run the code in Java?

I was trying to execute the following code in java:
import java.awt.*;
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
public class TextEditorDemo extends JFrame {
private static final long serialVersionUID = 1L;
public TextEditorDemo() {
JPanel cp = new JPanel(new BorderLayout());
RSyntaxTextArea textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
RTextScrollPane sp = new RTextScrollPane(textArea);
cp.add(sp);
setContentPane(cp);
setTitle("RSyntaxTextArea 1.4 - Example 1 - Text Editor Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Start all Swing applications on the EDT.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextEditorDemo().setVisible(true);
}
});
}
}
Since I'm using RSyntaxTextArea file i have to give the classpath of it while I'm running the code.
Assume that my RSyntaxTextArea.jar file is in Anto(i.e. my Home directory in Ubuntu 10.10) and when I run the above code:
javac -classpath \Anto\RSyntaxTextArea.jar TextEditorDemo.java
Still I'm getting the error as RTextScrollPane could not be found kind of errors. I guess i have been giving my classpath wrongly; What to do?
Thanks for the answer.
Did you download it from the sourceforge site? It is a zip file containing the sources. Create a folder for containing the sources and unzip it. Run ant in the folder - it will create a rsyntaxtextarea.jar in the dist folder. Add this to the class path.
Assuming that /Anto is really your home directory, try this:
javac -classpath ~/RSyntaxTextArea.jar TextEditorDemo.java
Otherwise, just point to a relative path to the jar file. For one thing, you were trying to use \, where in Linux you should be using /. You can reference the current directory with . So, if the jar is in your current working directory, you can just do this:
javac -classpath RSyntaxTextArea.jar TextEditorDemo.java
Or this:
javac -classpath ./RSyntaxTextArea.jar TextEditorDemo.java
If the Anto directory is under the current directory, use this:
javac -classpath ./Anto/RSyntaxTextArea.jar TextEditorDemo.java
Because that's not the path to your home directory, nor the correct slash to use.
javac -classpath /home/Anto/RSyntaxTextArea.jar TextEditorDemo.java
Also note Java 6 allows you to use a wildcard (*) for the path to search for jar files.

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 *.*
?

Categories