How to start a java program? - java

I have written a java program and I am running it through command line like "java MyProgram"
Now I want to have a GUI that have a start, pause and stop button. How to start that java program by clicking on start button. How to pause it and how to stop it?

I assume your program is something like:
public class MyProgram {
public void doSomething() {
// ... does something ...
}
public static void main(String[] args) {
new MyProgram().doSomething();
}
}
I recommend reading the Swing Tutorial, but a simple GUI to launch your program could be something like:
public class MyProgramLauncher {
public static void main(String[] args) {
final MyProgram myProgram = new MyProgram();
JFrame frame = new JFrame("My Program");
JComponent cp = frame.getContentPane();
cp.add(new JButton(new AbstractAction("Start") {
public void actionPerformed(ActionEvent e) {
myProgram.doSomething();
}
}));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
If your class has a pause() function, you could add a similar JButton to call that function, but you'd have to write/implement the function.
You would, however, have to launch this with java MyProgramLauncher, which isn't very exciting. Still, that will get you a basic GUI in which you can experiment with starting, pausing, etc.
To turn your program into something you can double-click on, you'll need to create a JAR file. This is basically a special ZIP file that includes all the classes in your application, plus a manifest.xml file that describes those classes and (for launchable JAR files) identifies the "main class" whose main() method should be called when the JAR file is launched.
To turn that JAR file into a more or less self-contained deployable application is a bigger pain and there are a whole lot of options. The Deployment Tutorial might be a place to start.

Basically you need a native launcher, but I cannot figure out what do you mean exactly by "pause"... Sending the process to sleep?
I think that should be very easy to implement with a shellscript using the xdialog command in a Unix like system.
You'll need to implement a state machine:
State: "Stopped"
Start: execute java YourProgram and store the PID in a variable. Change state to "Started"
Pause: do nothing/disabled
Stop: do nothing/disabled
State: "Started"
Start: do nothing/disabled
Pause: send the STOP signal (like ctr+z) to the process. Change state to "Paused"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
State "Paused"
Start: do nothing/disabled
Pause: send the CONT signal (like doing fg) to the process. Change start to "Started"
Stop: send the INT signal (like ctr+c) to the process. Change state to "Stopped"
With this, you can loop in the script and react to the buttons. Look the reference for kill and dialog or xdialog for more details on the implementation.

First you need to write your "Forms"...
This will be a helpful resource to a beginner.
Basics

Related

Create a stoppable java program (daemon)

Starting a java command line application is easy, you only have to write the following line in a command prompt (in the directory where the app is located).
java myApp.java
However, to stop the application in the right way, so that you ensure that all unmanaged resources are cleaned (and anything that must be done before stop, will be done) requires custom code.
The app will run in a debian system with no GUI as a daemon (it will run in background).
Here below I write the skeleton of the code.
public class MainClass {
public static void main(String[] args) throws Exception {
boolean stop = false;
while(!stop){
doSomething();
}
stop();
}
private static void doSomething(){
//Main code of app here
}
private static void stop(){
beforeStop();
System.exit(0);
}
private static void beforeStop(){
clean();
//Code to do anything you have to do before stop
}
private static void clean(){
//Code to clean unmanaged resources
}
}
As you can see, the app will run 24/24 and won't stop until you don't stop it.
Killing the process (as some people suggest) is not a good solution, because (for example) some unmanaged resources might not be cleaned properly.
I need a code which makes possible to alter the boolean variable "stop" from OUTSIDE.
The best solution is the one which makes possible to stop the app with a command similar to the start command, see pseudo code below (executed in a command prompt, in the directory where myApp.java is located).
myApp.java stop=true
But if it's not possible, the second option would be to have an other java command line app, which stops myApp.java, so that I could stop myApp.java with the following code
java stopMyApp.java
Is someone able to suggest a useful code example?
You can use a text file with one word. Your program reads it every x seconds and depending on that word it will autostop.
You can change the file text content by hand or with another program you can run whenever you want.
Even better you can use WatchService API (Java 7) or VFS API from Apache Commons to be notified when the file changes.
If you use a DB you can use it instead of a plain file.

How to prevent ctrl+c killing spawned processes in Java

[NB. This is related to How do I launch a completely independent process from a Java program? but different]
I want to be able to spawn external processes (shell scripts) from a "manager" Java process that should keep running when the JVM is killed - but it seems that when I kill the parent Java program the child is killed too (note, the behaviour is different if the JVM exits naturally). The simplest test program I have is:
public class Runit {
public static void main(String args[]) throws IOException, InterruptedException {
Runtime.getRuntime().exec(args[0]);
// doesn't work this way either
// ProcessBuilder pb = new ProcessBuilder(args[0]);
// pb.start();
while (true) {
System.out.println("Kill me");
Thread.sleep(2000);
}
}
}
and external script:
#!/bin/sh
while [ 1 ] ; do
ls
sleep 1
done
run as
java -classpath jar-with-dependencies.jar temp.exec.Runit runit.sh
If the manager simply exits (i.e. take out the "while" loop in the Java program) then the spawned process keeps running, but when I Ctrl+c the Java program the external program is killed too which is not what I want.
I'm using OpenJDK 1.6 on Ubuntu.
Edit1: Changing the exec to
Runtime.getRuntime().exec("/usr/bin/nohup " + args[0]);
doesn't help.
Edit2: Adding a shutdown hook as described in How to gracefully handle the SIGKILL signal in Java doesn't stop the Ctrl+c being propagated to the child.
Vladimir gave the hint we needed! (Sorry, beat Lukasz to it)
Add another script spawn_protect.sh
#!/bin/sh
LOG=$1
shift
nohup $* > $LOG 2>&1 &
And change the manager to:
public class Runit {
public static void main(String args[]) throws IOException, InterruptedException {
Runtime.getRuntime().exec(args);
while (true) {
System.out.println("Kill me");
Thread.sleep(5000);
}
}
}
Then run as:
java -classpath jar-with-dependencies.jar temp.exec.Runit spawn_protect.sh /tmp/runit.log runit.sh
Now runit.sh is really detached from the JVM process!
In Linux, if you start another process, it is your child and you are his parent. If parent gets killed, all children get killed, and their children too (what a terrible atrocity).
What you need, is to start a process that won't be killed when you exit your program. So, you need to give birth to not your own child. The methods to do that are described for example here: Linux: Prevent a background process from being stopped after closing SSH client for example use screen utility.
You've got to make it a daemon. Don't be afraid it's not a horror movie. Simply you'll need to detach your processes from controlling terminal session. I've always do it in a oposite way: shell script that launches Java.
Here is an explanation:
http://en.wikipedia.org/wiki/Daemon_(computing)
You can also you "jvm shutdown hooks", but they will not work in some situations.

How can I pause a Java splash screen from a batch file?

I have the simple batch file code, which is working:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg GUI
However, it only takes like 1 second for my GUI class-file to load, and then the splash-screen immediately closes and launches the program.
I want to make the splash-screen wait for 5 seconds. My idea was to first execute the splash-screen without the class-file, to use TIMEOUT, and then to execute the class-file like this:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg
TIMEOUT 5
java GUI
This isn't working correctly either. The splash-screen is then displayed for some milliseconds and is closed immediately. The command-line then waits for 5 seconds, and then the program is launched.
Any ideas on how to correctly do this from a batch file?
Thanks to Greg here, I have a solution where I am delaying the splash-screen from the main method using Thread.sleep.
Here is the batch file:
set path=%path%;C:\Program Files (x86)\Java\jdk1.7.0_05\bin
javac C:\Users\Ian\Desktop\batchFileTest\GUI.java
java -splash:images/splashImage.jpg GUI
...and here is the class with the main method:
class GUI {
public static void main(String[] args) {
try {
Thread.sleep(5000); // the parameter is in milliseconds
catch(InterruptedException e) {
System.out.println(e.getMessage());
}
/*
* do whatever stuff here
*/
}
} // end of GUI

close cmd + frame when click on the close button

hello i have a code that when runned opens cmd and then it opens the frame. i want the cmd to be closed as soon as the frame is opened or the cmd should be closed at the same moment as the user closes the frame. this is the code when i close my frame.
frame = new JFrame("BrainSla");
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
here is the main code:
public static void main(String args[]) {
try {
System.out.println("BrainSla - By Jannes Braet, Steven Brain, Wout Slabbinck.");
nodeID = 10;
portOff = 0;
setHighMem();
isMembers = true;
signlink.storeid = 32;
signlink.startpriv(InetAddress.getLocalHost());
new Jframe(args);
//instance = new client();
//instance.createClientFrame(503, 765);
} catch(Exception e) {
e.printStackTrace();
}
}
could someone tell me how i could do something like that ?
change frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); to
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This will exit the application as soon as you close the frame
If by 'cmd' you are referring to the 'command line' or CLI. Options:
Launch it from a bat file (or similar per OS) using javaw instead of java
Low learning curve.
Not very professional look.
Make it a runnable Jar (double click to open)
Medium learning curve.
Medium professional look.
Launch it using JWS
High learning curve.
Very professional look.
If you run from a command line closing the command line window will close your application prematurely. Not sure of any way to do it on Windows but on Linux you can background the process and do it using the command:
nohup java -jar myprogram.jar &
If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.
But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).
On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

Disconnect java application from console/command window [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is there a way to the hide win32 launch console from a Java program (if possible without JNI)
When I run my java swing application in a batch file on windows, the console/command window remains open whilst my java application is running. This creates an extra window on my taskbar which I would prefer not to have. But when I close the command window it stops my java application. Is there a way, perhaps via the batch file or command line parameters or code changes to my application, to have java.exe exit after bringing up my swing app and the console window close whilst my application still runs?
Main method is as follows:
public static void main(String args[]) {
ApplContext applContext = new ApplContext();
Throwable error = null;
try {
applContext.setUserConfigDir(args.length>0 ? args[0] : null);
applContext.loadData();
ApplTools.initLookAndFeel(Parameters.P_NIMBUS_LAF.of(applContext.getParameters()));
} catch (Throwable e) {
error = e;
}
// JWorkSheet is a JFrame.
new JWorkSheet(applContext, error).setVisible();
}
Run your application with javaw.exe rather than java. If you're running from a bat file, use this in combination with the start command:
> start javaw.exe -jar myapp.jar
When run in this mode, it's a good idea to set up proper logging or at least redirect your output streams if you rely on the console for any debugging. For example, with no console, you'll never see those friendly stack traces printed for unhandled exceptions.
Note: java.exe is a Windows console application. As such, no matter how it is started, or what threads are running in it, a console will be allocated for it. This is the reason that javaw.exe exists.
Ideally what you will eventually do somewhere in your code is call SwingUtilities.invokeLater(Runnable r). That will throw your GUI code into the correct thread, and you should be able to close the command line after the main thread exits.
This is a basic example of what I am talking about:
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame yourWindow = new YourFrame();
yourWindow.createAndShow();
}
}
}

Categories

Resources