I'm trying to close my main application user interface, but leave code running in my main() function that launched the application. Right now the problem I have is on a Mac the program name remains in Mac's menu bar even though there are no windows shown.
So basically in the code that would exit the application I have:
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
//System.exit(0);
this.setVisible( false );
// Do something here to finish closing application.
}
The main function that starts the application looks like:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// NewApplication is a javax.swing.JFrame
new NewApplication().setVisible(true);
}
});
while (true) {
// Watch for user to relaunch UI and do lots of other tasks.
}
}
If I used System.exit(0) it would stop the entire JVM completely and stop running the stuff in the while loop. I cannot figure out how to exit the main application UI, stop from showing in the menu bar, but still run the while loop stuff.
The reason I'm trying to do this is I need something that will run continuously and sometimes the user will need to run a user interface that interacts with the stuff that is running. The stuff inside the while loop checks to see if they are trying to launch the user interface again (among other functions) and would reload it. One option is to make one program that runs continuously and use inter-process communication to talk between the user interface and a non-UI program, but I would need to pass lots of data back and forth so I don't like that option.
It appears there is not an easy way of doing this. For those that have the same problem here are a few options:
1) It looks like other programs I have do this by using Mac’s task bar (in the upper right corner of the screen). The only way you access the program is through a menu on the task bar. Even when you have UI’s shown you get to the UI through the task bar. The downside of doing this is that when the UI is shown you can’t use Cmd+Tab to get over to the window. This is non-intuitive for Mac users. If you want to use this option you can start the java jar file with the command line option “-Dapple.awt.UIElement="true”” and that will prevent the program from showing a menu ALWAYS, and then you'll want to create a task bar icon so the user can get to your program.
See How to hide the Java SWT program icon in the Dock when the application is in the tray
2) Have 2 programs that run, one with a UI and another without. They can communicate using interprocess communication (IPC) using files, sockets, etc. If you don’t have much data to pass between the processes, this is a good solution.
3) You could probably use JNI to remove the menu on the application after all the UI’s close. But you’ll need to dig into Mac’s Objective C language. I can't confirm you can actually do this though.
Related
I am new to Java programming and I know basic syntax of Java and can write programs.
I want to make desktop application in java that never lets the system sleep. I want that application to run in background and should not disturb the user flow.
I figured out some keyboard keys can be pressed internally which does not affect the flow like F13 F14 not shown to user but can be used internally.
Also I came with this java program that moves the mouse to its same position after some seconds so that system does not sleep.
import java.awt.*;
import java.util.*;
public class Mal{
public static void main(String[] args) throws Exception{
Robot mal = new Robot();
while(true){
mal.delay(1000 * 60);
mal.mouseMove(mouseLoc.x, mouseLoc.y);
}
}
}
I am curious to know how to make desktop app for windows using Java.
Like when user clicks on the app it get activated and keep running in the background until close by the user and it should never let the PC sleep either my moving mouse or by clicking special keys.
Useful links, code and path for development is required.
Thank You!
You could try using java.awt.Robot: https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
As the documentation notes, this will not work in all environments, because allowing user-space programs to emulate user input is a bit of a security issue.
This question already has an answer here:
How to stop Java from running the entire code with out waiting for Gui input from The user
(1 answer)
Closed 5 years ago.
I'm a rather basic programmer who has been assigned to make a GUI program without any prior experience with creating a GUI. Using NetBeans, I managed to design what I feel the GUI should look like, and what some of the buttons should do when pressed, but the main program doesn't wait for the user's input before continuing. My question is, how do I make this program wait for input?
public class UnoMain {
public static void main(String args[]) {
UnoGUI form = new UnoGUI(); // GUI class instance
// NetBeans allowed me to design some dialog boxes alongside the main JFrame, so
form.gameSetupDialog.setVisible(true); // This is how I'm trying to use a dialog box
/* Right around here is the first part of the problem.
* I don't know how to make the program wait for the dialog to complete.
* It should wait for a submission by a button named playerCountButton.
* After the dialog is complete it's supposed to hide too but it doesn't do that either. */
Uno Game = new Uno(form.Players); // Game instance is started
form.setVisible(true); // Main GUI made visible
boolean beingPlayed = true; // Variable dictating if player still wishes to play.
form.playerCountLabel.setText("Players: " + Game.Players.size()); // A GUI label reflects the number of players input by the user in the dialog box.
while (beingPlayed) {
if (!Game.getCompleted()) // While the game runs, two general functions are repeatedly called.
{
Player activePlayer = Game.Players.get(Game.getWhoseTurn());
// There are CPU players, which do their thing automatically...
Game.Turn(activePlayer);
// And human players which require input before continuing.
/* Second part of the problem:
* if activePlayer's strategy == manual/human
* wait for GUI input from either a button named
* playButton or a button named passButton */
Game.advanceTurn();
// GUI updating code //
}
}
}
}
I've spent about three days trying to figure out how to integrate my code and GUI, so I would be grateful if someone could show me how to make this one thing work. If you need any other information to help me, please ask.
EDIT: Basically, the professor assigned us to make a game of Uno with a GUI. There can be computer and human players, the numbers of which are determined by the user at the beginning of the game. I coded the entire thing console-based at first to get the core of the game to work, and have since tried to design a GUI; currently this GUI only displays information about the game while it's running, but I'm not sure how to allow the code to wait for and receive input from the GUI without the program charging on ahead. I've investigated other StackOverflow questions like this, this, this, or this, but I cannot comprehend how to apply the answers to my own code. If possible, I'd like an answer similar to the answers in the links (an answer with code I can examine and/or use). I apologize if I sound demanding or uneducated and confusing; I've been working diligently on this project for a couple weeks and it's now due tomorrow, and I've been stressing because I can't advance until I figure this out.
TL;DR - How do I get my main program to wait and listen for a button click event? Should I use modal dialog boxes, or is there some other way to do it? In either case, what code needs to be changed to do it?
Unlike console based programming, that typically has a well defined execution path, GUI apps operate within a event driven environment. Events come in from the outside and you react to them. There are many types of events that might occur, but typically, we're interested in those generate by the user, via mouse clicks and keyboard input.
This changes the way an GUI application works.
For example, you will need to get rid of your while loop, as this is a very dangerous thing to do in a GUI environment, as it will typically "freeze" the application, making it look like your application has hung (in essence it has).
Instead, you would provide a serious of listeners on your UI controls that respond to user input and update some kind of model, that may effect other controls on your UI.
So, to try and answer your question, you kind of don't (wait for user input), the application already is, but you capture that input via listeners and act upon them as required.
I want to save information from last window (there is possible to use a couple of window in my program) before closing java fx app.
I tried to do this in stop() method, but it saves first opened window.
using Platform.exit() stops whole app after closing randow window.
I tried to do some special main window and let user save chosen window by using extra button, but it's not the prettiest solution.
How can I save last used window? Is there any event handler which is gonna solve my problem?
Yes there is, a few ways you could try...
1) Inside of your Application class, in the Application#launch method, specify the onCloseRequest event
yourStage.setOnCloseRequest(event -> {
//Do Your on close events here
});
2) Inside of your Application class, override the Application#stop method
#Override
public void stop(){
//Do Your on close events here
}
And alternatively, you can specify a system shutdown hook for when the jvm exits, which you can do like so
Runtime.getRuntime().addShutdownHook(() -> whatToDoOnExit());
I've created a visualizer in JavaFX for a problem I'm solving, and currently I can get it to show up after the calculations in my application are done, but I would like the window to first be opened and then run the calculations, so I can animate the visualization during the computations.
This is the code for creating an instance of the problem, showing the visualizer and performing the calculations:
public static void run(Visualizer v) {
readInput();
if (v != null) {
v.resizeCanvas(rectangles);
v.drawAllRectangles(rectangles);
v.show();
}
calculateArea();
System.out.println(totalArea);
}
The Visualizer class extends javafx.application.Application and utilizes a JavaFX Canvas. calculateArea() simply runs a static method which performs some calculations.
What currently happens when I run my program is:
It waits for input on stdin
The computations are run
The visualization is displayed
What I want:
It waits for input on stdin
The visualization is displayed
The computations are run
So for some reason the displaying of the visualization is delayed even though I call v.show() before calculateArea().
My first hunch would be to run the calculations in a new thread, but according to
the documentation "The JavaFX scene graph, which represents the graphical user interface of a JavaFX application, is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread."
I tried putting a Thread.sleep(3000) right after v.show(), and what happened was that my program just waited 3 seconds before running calculateArea() followed by the window being displayed.
Thanks for any input!
You should call your calculation method in a separate thread (as suggested by #Selim) launched in the applications start() method.
If your calculation method directly changes graphical content on screen (which it should not do BTW...) you need to pass this graphics code (not the calculation itself) to Platform.runLater().
Depending on a command line argument or virtual machine argument I'd like my application to start in an invisible mode. It does the same things in both cases, except that in invisible mode it simply doesn't display anything.
I can make the main program window invisible using JFrame.setVisible(false). However, then I have to find every place in the code, where for example a warning message pop-up is opened etc. (there are a lot of those!).
Is there a more general way to do that? May-be something like the headless mode (which of course throws HeadlessExceptions which is not what I want).
Thanks!
What does your applications architecture look like? If it is cleanly separated then create a new View layer that does nothing.
If it is tangled up together, the best option would be to un-tangle it and then create a new view layer that does nothing.
Do like this.
public static void main(String[] args){
boolean gui = true;
for (String s : args){
if (s.equals("--nogui")){
// Do not create GUI
gui = false;
break;
}
}
if (gui){
// Create the gui
}
}
If your presentation layer is tightly coupled with business logic you will have to do check in all your forms, and other visible classes. You should decouple your application, and than it would be as easy as calling one method.
In other case... well you will have a bunch of if else if.