How to open your eclipse project in a window? - java

How do I export my Eclipse project so that it is its own console application sort of thing.
Every time I try to run the .jar file after exporting it, a window pops up saying that it couldn't open the program. Is there some code I need to enter in order to make it its own window, like when you run it in eclipse, except it is its own window and application. Here is an example of how I have coded it:
public class main {
public static void main(String[] args) {
Scanner text = new Scanner(System. in );
System.out.println("Ready:");
boolean loop2 = true;
while (loop2 = true) {
String text1 = text.nextLine();
switch (text1) {
case "hi":
System.out.println("Greetings!");
break;
}
}
}
}
Any help would be nice! I am trying to make this for sending to my friends, too, just so you know.

In the navigator view, right-click on your project > Export > Java > Jar. Be sure to indicate your class as main class.
Then, once saved, you can run the jar by double clicking on it, or using java -jar jarfile.jar from command line.

Related

IntelliJ Idea - Cannot find input file(bank.in) when running through IntelliJ

I have a homework and I did it on Linux, Visual Studio Code, and the command line. It was working perfectly fine until I need to debug my code. So I migrated to Windows 10 because I had IntelliJ IDEA installed there. I compiled the code and place the input file "bank.in" in the same folder as the compiled "MyClass.class"
However, when I run the program from IntelliJ, my code catches the exception that it cannot find the file "bank.in" when it is just in the same folder as "MyClass.class".
My method in creating the bank.in was, right clicking the out folder from IntelliJ and adding a new file and adding the bank.in contents from there
I've tried running it through cmd.exe using java MyClass and it works perfectly. No exceptions are caught.
But when run through IntelliJ IDEA, it shows
Cannot find bank.in...
Exiting the program...
This is the part of my code where I input my file.
public void main(String[] args)
{
String fileName = "bank.in";
FileReader bank = null;
BufferedReader bankBuffered = null;
try
{
bank = new FileReader(fileName);
bankBuffered = new BufferedReader(bank);
}
catch(FileNotFoundException f)
{
System.out.printf("%s is not found.%n%n", fileName);
System.out.printf("Exiting the program...%n");
System.exit(0);
}
}
This is my project folder structure
MyProject
-.idea
-encodings.xml
-misc.xml
-modules.xml
-workspace.xml
-out
-MyClass.class
-bank.in
-src
-MyClass.java
When I run it through cmd.exe, it works fine. Is there any workaround through this? Thank you.

Is there a way to run a -.jar file (created with javaFx) without displaying anything(GUI, progressbar, ...)?

I wrote a java file including javaFX. Now, I want to run this file, like
java -jar example.jar
But I'd like to suppress the graphical output.
Is there any possible, like a flag or anything else, to do this?
My program normally shows a progressbar and after that a video of the simulation.
Thanks a lot.
To elaborate on JB Nizet's comment.
JAR files have manifests. In order to run your JAR using the command java -jar example.jar, the manifest must have a Main-Class entry. And your main class must have a main() method.
So launch your app like so...
java -jar example.jar NO_GUI
And in your main() method, write something like the following...
public static void main(String[] args) {
if (args.length > 0 && "NO_GUI".equals(args[0]) {
// Don't show GUI
}
else {
// Show the GUI.
}
}
You could call hide() on the scene so the window dissapears.
There is not really a way to force this.
Instead, implement it as feature. Create a command line argument nogui and react to it:
public static void main(String[] args) {
boolean useGui = true;
if (args.length > 0 && args[0].equals("nogui")) {
doNotUseGui = false;
}
// Create your program and give it the flag
Program prog = new Program(useGui);
...
}
Note that theoretically it would be possible to hack your application and remove any such calls, or to suppress the calls on a native level. But I guess that is not really the route you want to go.

Make an extendable java program

I'm making a java command prompt (like the Windows CMD).
But I want to make it possible for other developers to add some commands to my program by putting their own *.jar files in a folder called "extensions".
I know this is possible because Minecraft can be modded with MC Forge like that (by putting your mod jars in a folder called "mods")
Example:
public class myExtension extends Extension {
//A method called by my program
#Override
public void onLoad() {
//Register a command in the main class...
Command cmd = Commands.registerCommand("hello");
//Add an event listener...
cmd.addEventListener(new CommandEventListener() {
public void onCommandExecute() {
//Print "Hello World !" to console when the command is executed...
Console.getConsole().print("Hello World !");
}
});
}
}
So now the guy who made this should be able to export this program as a jar file and put it in the "extensions" folder. But how can I make that my program register this jar as an extension ?
I you know the answer the please write it down ! Thank you !

Update java desktop app

I am trying to develop a module that can update my running Java Desktop App.
The problem is that I have to replace the actual running jar with another jar, all the while displaying an image and a progress bar with the remaining time of the update process.
One solution I thought about is that I can put a jar in my main jar, and when launching the update process, to extract that second jar which will display the image and the progess bar, and also which will replace the old main jar with a new main jar.
My question is if this is possible and how can I do it.
I do not have a lot of experience with java and java packaging so if you have any examples or links, it would be of great help for me.
Thank you very much.
R.
Run this code when press UPDATE button ..
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().open(new File("update.jar"));
System.exit(0);
} catch (IOException ex) {
}
}
This will open update.jar and close main.jar. Now run this code from main class of update.jar
//wait sometime for terminate main.jar
try{
Thread.sleep(5000);
} catch(Exception e){
e.printStackTrace();
}
if(isUpdateVersionAvailable()) { //first check update from database
if(copyMainJarFileFromServer()){ //copy newMain.jar from server and paste
new File("main.jar").delete(); //delete main.jar
rename(new File("newMain.jar")); //rename newMain.jar to main.jar
}
}
boolean isUpdateVersionAvailable() {
//todo
}
boolean copyMainJarFileFromServer() {
//todo
}
void rename(File file){
file.renameTo(new File("main.jar"));
}
You can have a starter jar that checks for updates and launches the app from the main jar.
It will show start logo, an image, that standard java can display at start-up.
The start0er could also be used to restart the app in another interface language.
package starter;
...
public class StarterApp {
public static void main(String[] args) {
String workDir = System.getProperty("user.dir");
Path mainJar = Paths.get(workDir + "...");
Path nextMainJar = Paths.get(workDir + "...");
if (Files.exists(nextMainJar)) {
Files.copy(nextMainJar, mainJar, StandardCopyAction.REPLACE_EXISTING);
}
URLClassLoader classLoader = new URLClassLoader(new URL[] {mainJar.toURL()});
Class<?> appClass = classLoader.find("mainjar.MainApp");
... instantiate the app
}
As you see the main jar must not be loaded from too early, maybe not be on the class path entirely, and hence the use of a separate ClassLoader. The same might probably be done with the main jar on the class path of the starter app, and using Class.forName("mainjar.MainApp"). The Class-Path can be specified in META-INF/MANIFEST.MF.
The secundary jars may reside in a lib/ directory.
For those readers wanting more modular, service oriented, updateable apps, one could make an OSGi application, a container for bundles (=jars), that provide exchangable services and life-time control.

.jar file won't run? (I feel like I'm missing something obvious, looked to solutions myself before coming here.)

I wanted to find out how to create an executable .jar file, so I wrote a small sample program to test it. This sample program takes some default text and turns it into some code based on the Caesar code. Anyway, it outputs normally when run in Eclipse.
I doubt this helps, but here's the source code for the two java classes.
Main.java
public class Main {
public static void main (String [] args){
Caesar caesarCode = new Caesar();
caesarCode.setDecodedText("this");
caesarCode.setShiftPos(3);
String cipherText = caesarCode.deencode(caesarCode.getDecodedText(), caesarCode.getShiftPos());
System.out.print(cipherText+"\n");
String plainText = caesarCode.deencode(cipherText, caesarCode.getShiftPos()*-1);
System.out.print(plainText);
}
}
Caesar.java
public class Caesar {
// global variables
String encodedText; // encoded text
String decodedText; // decoded text
int shiftPos; // shift positions to decode message
// getters and setters
public String getEncodedText() {
return encodedText;
}
public void setEncodedText(String encodedText) {
this.encodedText = encodedText;
}
public String getDecodedText() {
return decodedText;
}
public void setDecodedText(String decodedText) {
this.decodedText = decodedText;
}
public int getShiftPos() {
return shiftPos;
}
public void setShiftPos(int shiftPos) {
this.shiftPos = shiftPos;
}
public String deencode (String plainTextArg, int shiftPosArg) {
// variables
String plainText = plainTextArg;
char[] cipherTextArray;
String cipherText;
int plainTextSize;
int shiftPos = shiftPosArg;
// initialize variables
char[] plainTextArray = plainText.toCharArray();
plainTextSize = plainTextArray.length;
cipherTextArray = new char[plainTextSize];
// shift cipher String by shiftPos
for (int i = 0; i < plainTextSize; i++){
cipherTextArray[i] = (char) (plainTextArray[i] + shiftPos);
}
cipherText = String.valueOf(cipherTextArray);
// return cipher text
return cipherText;
}
}
I created my .jar file this way (on a Mac):
Created two directories on Desktop: "classes" and "source"
Copied my two files (Caesar.java, Main.java) into the source folder.
I compiled the files into .class files in the classes directory with the command "javac -d ../classes *.java"
I created a manifest.txt file with the line "Main-Class: Main", and saved it as "manifest.txt" in the classes directory.
I then created the .jar file with this command "jar -cvmf manifest.txt main.jar *.class".
The main.jar file was created successfully.
The problem is, when I ran it, nothing happened - no warnings, no popups, no error messages.
I'm thinking that it has something to do with the fact that it outputs to the terminal, but I can't wrap my head around it. I've also looked at many threads on this forum and others, but can't seem to see the problem. I'm going to experiment to see if it works for a GUI application in the meanwhile.
Greatly appreciate your help on this, thanks!
I'm thinking that it has something to do with the fact that it outputs to the terminal
If you want to see console output from your program then you will have to run it in the Terminal with java -jar main.jar. If you double click the JAR in the Finder or use the open command then it will run but any output will go to the system console log rather than being displayed directly. You can show system console messages by running syslog -C.
In Windows, press Windows+R to invoke "Run..." dialog. Type cmd there and hit Enter. The Command Prompt window will appear (it's black).
At the prompt type cd %USERPROFILE%\Desktop\classes and hit Enter.
Then type command as suggested above: java -jar main.jar
It is possible to create executable jars from within eclipse if you want to.
Right click on your project -> Export -> Java -> Runnable JAR file.
Note that You might need to run your jar file from the command line using java -jar <jarFile> to see System.out.println() and error messages.

Categories