I have been searching the internet, but I can't find a solution for this. My program works fine in Eclipse, but I have to make the program into a .jar file so the user can just click on the .jar file and the GUI will run.
When I click on the .jar file that I exported, nothing happens. There is just the main class of the program and if I click run in Eclipse, the GUI will come up.
What do I need to add in here so the GUI will stay and not disappear straight away? I tried to put a JOptionPane in there and it works, the box will come out but the GUI will not still.
package dijkstra;
import java.awt.BorderLayout;
import java.util.Map;
import javax.swing.JFrame;
public class RunGUI {
public static void main(String[] args){
FlightSchedulerGUI.setWindowsLookAndFeel();
try {
Map<Integer, Airport> airports = FileProcess.loadtegMap();
FlightSchedulerGUI GUI = new FlightSchedulerGUI(airports);
GUI.randomizeRoute();
GUI.findBestRoute();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(GUI);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flight Scheduler");
frame.setSize(600,400);
frame.setVisible(true);
} catch(Throwable t ){
t.printStackTrace();
System.err.flush();
System.exit(1);
}
}
}
Ensure you have added the Main-Class attribute to the MANIFEST file of your jar file.
Example:
Main-Class: dijkstra.RunGUI
The file must be called MANIFEST.MF and must be placed to META-INF folder, within your jar file.
More info
Related
I just programmed my first JFrame and exported it, but I'm not able to run the .jar file normally. When I try to run it using Terminal, it works without any problems. However, when I try to open the file normally by double clicking on it, I get an error message similar to this: The Java jar file "Programm.jar" could not be launched.
Here's the code (maybe there's something wrong with it?):
package GUI;
import javax.swing.JFrame;
public class Frame {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setSize(500, 300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setTitle("Programm");
jf.setResizable(false);
}
}
Thanks in advance!
I think you need to associate the file type with the java executable, then the Finder will know what to do when you double click
I'm following along with this tutorial, and I got a problem early in the video (at approximately 7:45). I'm trying to create a basic Java program that will launch a window, however, I can't seem to import JFrame.
I've looked for other solutions on Stack Overflow, but I haven't found one that works for me.
Here is the code I've written:
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World");
frame.setVisible(true);
}
}
I'm using Eclipse version 4.12.0 on a Macbook Pro (13-inch, Mid 2012) running macOS Mojave version 10.14.5
Expected result: A window opens when I run the program, and when I close the window, the program ends.
Actual result: No window is created and I get this error message:
Error occurred during initialization of boot layer
java.lang.module.FindException: Error reading module: /Users/username/eclipse-workspace/Swing1/bin
Caused by: java.lang.module.InvalidModuleDescriptorException: App.class found in top-level directory (unnamed package not allowed in module)
If you have a module-info.java file, put this in the module:
requires java.desktop;
If you have created the java app with eclipse your fault is the package.
With eclipse, I created a java app and this is the result
This code fixed your foult
package demo;
import java.awt.Dimension;
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World");
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(400, 400));
frame.setVisible(true);
}
}
The reference for understand the package
I had the same issue. I did similar code in Eclipse. I got the error The type javax.swing.JFrame is not accessible on the side of import javax.swing.JFrame;
The solution is:
Delete the line of import javax.swing.JFrame;
And then, inside your body of your code inside your main, with your mouse, hover over JFrame keyword, and Eclipse will offer some auto-completion suggestion.
Select import 'JFrame' (javax.swing)
This will bring the required import automatically. It is a kind of shortcut.
In order to avoid these type of errors: Never type manually, get the imports AND methods, for example setVisible by autofilling. For instance, type frame.setV and again Eclipse will suggest the completion ... select from there. I do not know why, but this is what happened in my case.
I tried building simple Swing forms using IntelliJ's GUI designer tool and noticed some things I don't like (at least till I don't understand). For this question lets consider a very simple Swing form with just one button. I opened up GUI designer and added a button( 'load file') to the middle of mainPanel using GridBagLayout. The java code it generated (I wrote the main method myself):
package mainPackage;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Povilas on 06/01/2017.
*/
public class MainFrame {
private JButton loadFileButton;
private JPanel mainPanel;
public MainFrame() {
loadFileButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"This should be a browser dialog...");
}
});
}
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
JFrame frame = new JFrame("App");
frame.setContentPane(mainFrame.mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
If i run this code it works, which is crazy and unexpected, because nowhere in the code loadFileButton is initialized, nowhere in the code mainPanel is initialized, nowhere in thecode is LayoutManager added or button added to the panel. If i tried compiling this code from cmd I would get NullPointer exceptions in the constructor because button and panel are not initalized.
Question:
How come intelliJ compiles and runs the app successfully? Does it process .form file at compile time to add missing code? I want to design Swing dialogs with IntelliJ's designer but to get proper, full code which could then be compiled and packaged a from cmd using javac and jar, how do I do that?
The code below works fine in Eclipse (both image-handling possibilities). But when exporting as a Runnable JAR File, and double-clicking the .JAR, nothing happens. If I comment out the image parts of the code, the .JAR runs fine as an export and the frame builds. So it seems the getting of the image is causing the .JAR to fail.
I've got the strawberry.jpg file sitting in 'C:\Users\sean\workspace\myApps\bin\testing' Could you advise if the issue is with my code?
(Code first modified here: Java Swing: unable to load image using getResource)
package testing;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
public class IconTest {
public static void main(String[] arguments) throws IOException {
JFrame frame1 = new JFrame();
frame1.setTitle("Frame1");
frame1.setSize(500, 500);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
frame1.setLayout(flo);
//POSSIBILITY 1 TO HANDLE IMAGE
InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
Image image = ImageIO.read(resourceAsStream);
JLabel label1 = new JLabel(new ImageIcon(image));
//POSSIBILITY 2 TO HANDLE IMAGE
/* java.net.URL url= IconTest.class.getResource("strawberry.jpg");
BufferedImage watermarkImage = ImageIO.read(url);
JLabel label1 = new JLabel(new ImageIcon(watermarkImage));*/
frame1.add(label1);
frame1.setVisible(true);
}
}
Put the image where you have the source file because it points to the source directory
InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
and then generate runnable jar file and then right click the jar and give run as java platform binary
POSSIBILITY 3 TO HANDLE IMAGE :
You can check that resource that you are fetching is exist or not. It resource not found then you can create JLabel with alternative text also...
JLabel label1 ;
URL imageUrl = IconTest.class.getClassLoader().getResource("strawberry.jpg");
if ( imageUrl != null ) {
label1 = new JLabel(new ImageIcon(imageUrl));
} else {
label1 = new JLabel("Alternative text");
}
Following Maven standard directory layout might be helpful:
InputStream resourceAsStream = IconTest.class.getResourceAsStream("/strawberry.jpg")
It should start from "/". Also check whether the jar actually have the image. Just unpack it and check whether the image is actually added.
The guidance offered here in troubleshooting the problem helped greatly - thank you to everyone. I tested contents of an exported JAR; I used diagnostic code suggested by Kishan to determine if my code could "see" the image. I believe it might have something to do with the way Eclipse works/refreshes if I move images around in the file system instead of the Eclipse import function.
Finally, in order to get it to work, I made the following changes:
I created a new project and two sub-packages - one for 'resources' and one for my code class. Then I right-clicked > import on the resources package in Eclipse to get the image.
The only thing to change in my code is ....getResourceAsStream("/resources/strawberry.jpg");
package mainClasses;
/*
* Frame Info and all that ****,
* mainFrame is the actual frame itself
* it will refer to MainC.java a lot Main class = Main Class
*/
import java.awt.FlowLayout;
import java.awt.Graphics;
import JavaGame.src.resources.*; //Problem Code
import javax.swing.JButton;
import javax.swing.JFrame;
public class mainFrame extends JFrame {
private static final long serialVersionUID = 1L;
public mainFrame() {
JButton playButton = new JButton();
JButton infoButton = new JButton();
JButton exitButton = new JButton();
int x = 300, y = 300;
setSize(x, y);
setVisible(true);
setLayout(new FlowLayout());
setTitle("Kingdom Raider");
setDefaultCloseOperation(EXIT_ON_CLOSE);
/*Buttons and Properties*/
playButton.setBounds(x, y, 200, 100);
playButton.setText("Play!");
add(playButton);
infoButton.setBounds(x, y, 200, 100);
infoButton.setText("Information");
add(infoButton);
exitButton.setBounds(x, y, 200, 100);
exitButton.setText("Exit");
add(exitButton);
/* Add image here */
}
public void Painting (Graphics g) {
//Me.
}
}
I'm creating a game and I'm having an import problem.
As you can see I want to import JavaGame.src.resources, as I'm trying to import an img.
Here's how my Directory stands:
I don't need to know the code on resourcesmanager.java its blank at the moment.
So basically, this class here is in packages mainClasses, but i want to access the resources package. What gives?
Your package name is resources, so write this:
import resources.*; // No-Problem Code
The remaining parts of the directory structure is specific to Eclipse and doesn't have anything to do with Java classpaths
Your source folder is src, so this is the root of your class hierarchy. You should do
import resources.*
However using * is bad form and you should try and import only classes that you need in this particular class, like you've done with javax.swing.JButton for example. So:
import resources.ResourceManager;
Resources aren't imported like packages. Have a look here: http://docs.oracle.com/javase/1.5.0/docs/guide/lang/resources.html.
Specifically, here's an example how to load images from resources: http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource.
Eclipse will automatically import stuff for you if you copy and paste something-maybe you could write a short clip that uses something in JavaGame.src.resources, and then copy paste that-eclipse will do the rest.
I think this could be a problem with Eclipse configuration. Sometimes Eclipse considers the source folder in the project as part of the package. Just delete the project from the Eclipse workspace without deleting it from the file system and import it again.
That should help.
Deleting project from eclipse without deleting it from the file system:
http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-42b.htm
Importing existing project into eclipse:
http://agile.csc.ncsu.edu/SEMaterials/tutorials/import_export/
What you want to do is access the files stored in your resources folder. To do this, you don't import the folder as you tried to do. Instead, do what Tony the Pony advised and use
getResource("FileName.ext")
As an example, to turn a file into an icon, you'll have to use the resource path:
java.net.URL path = this.getClass().getResource("FileName.jpg");
ImageIcon icon = new ImageIcon(path);
I should also point out that if you're using NetBeans, you need to add the resource folder as a source folder; otherwise the project won't compile how you want it to, resulting in a .jar file that can't access the resource files. Eclipse might be similar. To add the folder as a source:
Right click on project
Select properties
Click "Sources" in categories pane
Click "Add Folder" and select the resource folder you made