Java Swing window not appearing in Eclipse - java

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.

Related

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.

Deploying a JApplet: ClassNotFoundException

Edit 2: I created a html in the root directory and placed the jar file in the same place, I could then get the applet to run (though I had some issues with self-signed security). This tells me the problem is in the applet code. Any ideas why it wouldn't find the class when if I can remove the codebase attribute it runs correctly?
Edit 1: I have updated the entry point to remove the frame. I also tested with the HelloWorld applet and still received the same error.
I'm fairly new to Java so I'll try to explain my problem as clearly as I can and with plenty of detail. If I miss anything please let me know. I'm also aware that this problem is frequently asked about on here, I've done a fair bit of research and found conflicting responses and nothing that worked.
I have developed a JApplet in eclipse, exported a jar file for the project and am attempting to deploy it on my website. However, when I attempt to view the applet online I get the error: ClassNotFoundException. It is probably also worth mentioning that I am trying to deploy this JApplet through wordpress.
Here is the html code I'm using to deploy:
<applet code = 'gui.ConverterGUI.class'
codebase = 'http://www.myurl.co.uk/Java/'
archive = 'AConverter.jar'
width = 800
height = 600>
<param name="permissions" value="all-permissions" />
</applet>
My applet has a few packages and classes which I think I have set up and exported correctly, but incase that is causing problems, here is my main entry point:
public class ConverterGUI extends JApplet {
// Current program ver.
public static final double VERSION = 0.0;
public void init() {
// Make it look nicer.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
//JFrame f = new JFrame("Converter GUI");
ResultDisplay resultDisplay = new ResultDisplay();
getContentPane().add(resultDisplay, BorderLayout.CENTER);
getContentPane().add(new InputFields(resultDisplay), BorderLayout.NORTH);
}
}
This is my project layout.
I've exported the jar using Eclipse, I've got the impression that this means it has been signed properly already, but if this is not the case and it is causing issues, I'd appreciate being pointed in the right direction to do this (I do have eclipse set up with the JDK rather than JRE).
The issue was in the html code and the way wordpress was interpreting it. For future reference, I fixed the issue by removing the lines from the html code and using double quotes, as follows:
<applet code = "gui.ConverterGUI.class" codebase="http://www.myurl.co.uk/Java/" archive="AConverter.jar" width=800 height=600><param name="permissions" value="all-permissions" /></applet>
Nonetheless I did get some useful advice here. Thanks all.

method must call super() error in Netbeans

Recently I've made a Netbeans project and I am using SVN along with it. I am seeing duplicate class error, and in the console it says
java.lang.VerifyError: (class: pie/chart/explorer/PieChartExplorer, method: <init> signature: ()V) Constructor must call super() or this()
Could not find the main class: pie.chart.explorer.PieChartExplorer. Program will exit.
Exception in thread "main" Java Result: 1
Here is PieChartExplorer.java:
package pie.chart.explorer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PieChartExplorer extends JFrame implements ActionListener {
JTextField one = new JTextField(10);
JTextField two = new JTextField(10);
JTextField three = new JTextField(10);
JButton sub = new JButton("Click to be amazed");
public PieChartExplorer() {
super("Pie Chart Explorer");
setSize(300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
setVisible(true);
add(one);
add(two);
add(three);
sub.addActionListener(this);;
add(sub);
}
public static void main(String[] args) {
PieChartExplorer app = new PieChartExplorer();
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == sub) {
try {
Pie show = new Pie(Float.parseFloat(one.getText()),Float.parseFloat(two.getText()),Float.parseFloat(three.getText()));
} catch(Exception ex) {
JOptionPane.showMessageDialog(this, "Please check entered data");
}
}
}
}
I have tried:
Clean and Rebuild project
Making sure that I have called super in all constructors
How can this be fixed? Code for download.
I found that renaming the package did not work, the old package was still there.
The problem for me started when I copied a package from another application into the current application, which already had a package with the same name. I was trying to add some missing classes to the package. After I did that, the error started.
To resolve it, I deleted the entire package from the target web app and did a clean and build. Then I copied the source package into the target application. No errors.
I saw these symptoms just the other day.
I had I file I had been editing and decided I wanted to split my changes into 2 commits. I went to the directory containing my file "x/y/Z.java", made a directory in "x/y" named "backup", moved "Z.java" there, and pulled a fresh copy from version control. Note all of this was done outside the IDE.
Back in the IDE I merged in the changes for the first commit and when I built I got the duplicate class message for "Z.java".
When I copied the source to "backup" I did it outside the IDE and it still had the original package "x.y" as did my newly edited "Z.java". NB would not compile the new "Z.java" because it could see it had already created "x.y.Z.class" (from "x/y/backup/Z.java").
There are 2 ways to fix this:
Rename "x/y/backup/Z.java" to "x/y/backup/Z.java.backup". (Prevent the backup copy from being compiled.)
Change the package in "x/y/backup/Z.java" from "x.y" to "x.y.backup". (Make the backup create a different class file.)
After making either of these changes, perform a "clean and build". Note: simply building will not fix the problem, you need to perform a clean to remove the rogue class file.
Note: #1 was done by renaming Z.java from the command line, not within NB. NB will not let you change the file extension.
Cleaning and Building solves the problem
If you still have the problem, this is how I solved it..
In my case I changed the class with main method later and the initial class was still referenced in the proporties file.
Change that setting, clean and build.. It worked for me...
In my case, i had the same problem in a Web application after making an external copy of a POJO and manually editing it outside NETBEANS. The problem actually was what the others suggested in other answers about a conflict in the already compiled .class files.
What i did to overcome this was simply delete the folder webAppname/WEB-INF/classes (where compiled classes reside) and then do a Clean and Build
Hope this helps someone

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