Как я создаю исполняемую программу Java? [дубликат]

Ваш конструктор DBManager(Context c) ожидает контекст в качестве параметра. Если вы вызовете этот конструктор из класса Activity или Service, он будет работать, так как Activity и Service являются подклассами Context, поэтому передачи this должно быть достаточно. Поскольку ActivityDummyDataManager не обрабатывает контекст, вам нужно передать контекст либо из действия, либо вы можете передать контекст приложения getApplicationContext().

Измените свой метод, как показано ниже

public static ArrayList<ActivityItem> getActivityItemList() {
        DBManager db = new DBManager(mContext);
        //rest of your code.
}

, и при его вызове используйте действие или контекст приложения в зависимости от того, что подходит.

54
задан nhahtdh 13 September 2013 в 20:37
поделиться

8 ответов

You can use the jar tool bundled with the SDK and create an executable version of the program.

This is how it's done.

I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.

First create your program:

$cat HelloWorldSwing.java
    package start;

    import javax.swing.*;

    public class HelloWorldSwing {
        public static void main(String[] args) {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel label = new JLabel("Hello World");
            frame.add(label);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
    class Dummy {
        // just to have another thing to pack in the jar
    }

Very simple, just displays a window with "Hello World"

Then compile it:

$javac -d . HelloWorldSwing.java

Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.

$ls start/
Dummy.class     HelloWorldSwing.class

Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.

This is the content of my manifest file.

$cat manifest.mf
Main-class: start.HelloWorldSwing

Just describe what the main class is ( the one with the public static void main method )

Once the manifest is ready, the jar executable is invoked.

It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.

$jar -cmf manifest.mf hello.jar start

This creates the .jar file on the system

enter image description here

You can later just double click on that file and it will run as expected.

enter image description here

To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.

Here's a video I've found about: Create a Jar File in Jcreator.

I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.

You can also use jnlp ( Java Network Launcher Protocol ) too.

64
ответ дан 7 November 2019 в 07:56
поделиться

Take a look at WinRun4J. It's windows only but that's because unix has executable scripts that look (to the user) like bins. You can also easily modify WinRun4J to compile on unix.

It does require a config file, but again, recompile it with hard-coded options and it works like a config-less exe.

3
ответ дан 7 November 2019 в 07:56
поделиться

As suggested earlier too, you can look at launch4j to create the executable for your JAR file. Also, there is something called "JExePack" that can put an .exe wrapper around your jar file so that you can redistribute it (note: the client would anyways need a JRE to run the program on his pc) Exes created with GCJ will not have this dependency but the process is a little more involved.

0
ответ дан 7 November 2019 в 07:56
поделиться

Вы можете использовать GCJ - для компиляции вашей Java-программы в собственный код.
В какой-то момент они даже скомпилировали Eclipse в нативную версию .

2
ответ дан 7 November 2019 в 07:56
поделиться

Я не совсем уверен, что вы имеете в виду.

Но я предполагаю, что вы имеете в виду одну из двух вещей.

  • Вы хотите создать исполняемый файл .jar

Eclipse может сделать это очень легко Файл -> Экспорт и создать банку и выбрать соответствующий Main- Класс, и он сгенерирует .jar для вас. В Windows вам, возможно, придется связать .jar со средой выполнения Java. aka Удерживая клавишу Shift, щелкните правой кнопкой мыши «открыть с помощью», перейдите к jvm и свяжите его с javaw.exe

  • , создайте фактический файл .exe, затем вам потребуется использовать дополнительную библиотеку, например

http: //jsmooth.sourceforge. .net / или http://launch4j.sourceforge.net/ создадут встроенную заглушку .exe с красивым значком, который по существу загрузит ваше приложение. Они даже выясняют, установлен ли у вашего клиента JVM, и предлагают вам его установить.

12
ответ дан 7 November 2019 в 07:56
поделиться

В командной строке перейдите в корневой каталог файлов Java, которые вы хотите сделать исполняемыми.

Используйте эту команду:

jar -cvf [name of jar file] [name of directory with Java files]

Это создаст каталог с именем META-INF в баночный архив. В этом META-INF есть файл с именем MANIFEST.MF, откройте этот файл в текстовом редакторе и добавьте следующую строку:

Main-Class: [fully qualified name of your main class]

, затем используйте эту команду:

java -jar [name of jar file]

, и ваша программа запустится:)

5
ответ дан 7 November 2019 в 07:56
поделиться

Взгляните на launch4j

1
ответ дан 7 November 2019 в 07:56
поделиться

Write a script and make it executable. The script should look like what you'd normally use at the command line:

java YourClass

This assumes you've already compiled your .java files and that the java can find your .class files. If java cannot find your .class files, you may want to look at using the -classpath option or setting your CLASSPATH environment variable.

1
ответ дан 7 November 2019 в 07:56
поделиться
Другие вопросы по тегам:

Похожие вопросы: