Frohman
Frohman

Reputation: 111

Java application only works when launched via a terminal/command prompt

I'm recently starting to learn Java and have had success writing and compiling my own application (written in Sublime Text, a text editor, and compiled via javac).

The application runs perfectly when launched via a terminal (or command prompt if I'm on my Windows PC), but if I try launching it from the file itself (in Windows, double clicking it and ensuring Java is the open-with method, or on my Ubuntu laptop, making it executable and doing the same) I get a very short lived loading cursor and then nothing.

The application (which converts between degrees Celsius and Fahrenheit) uses some simple Swing dialogs to get the user's input and to display the result.

import javax.swing.*;

public class DegreesConversion
{
public static void main( String [] args)
    {
    String input = JOptionPane.showInputDialog("Enter a temperature followed by either C for Celcius or F for Fahrenheit\nE.g. 30C or 86F");
    int degrees = Integer.parseInt(input.substring(0,input.length()-1));

    switch (input.toLowerCase().contains("f") ? 0 : input.toLowerCase().contains("c") ? 1 : 2){
        case 1:
            JOptionPane.showMessageDialog(null,(((degrees*9)/5)+32)+" degrees Fahrenheit", "Conversion complete", JOptionPane.INFORMATION_MESSAGE);
            break;
        case 0:
            JOptionPane.showMessageDialog(null,(((degrees-32)*5)/9)+" degrees Celcius","Conversion complete",JOptionPane.INFORMATION_MESSAGE);
            break;
        default:
            JOptionPane.showMessageDialog(null, "The input you entered was not recognised!","Unknown input", JOptionPane.ERROR_MESSAGE);
            break;

    }
    }
}

(This is by no means meant to be a serious or terribly functional application, it was simply my own attempt at making something in Java)

Anyhow, I'm not sure why this application, when compiled, only functions when launched from a CLI using "java DegreesConversion", and not when launched through a double click. I have looked for answers regarding this on Google and Stackoverflow, but haven't found anything near a relevant solution or hint as to why this is so.

I'm considering that Java .class files can't be executed the same as .jars? Any assistance would be greatly appreciated!

Upvotes: 1

Views: 1316

Answers (1)

stryba
stryba

Reputation: 2027

Package your class into a jar file and add a manifest to it pointing to the class having the main method you like to execute.

Then you can do java -jar jarFile.jar from terminal but it is also possible to easily to run it through, e.g., Windows Open-With capabilities.

EDIT: JAR tutorial

Upvotes: 5

Related Questions