This question already has an answer here:
How to wait for a JFrame to close before continuing?
(1 answer)
Closed 9 years ago.
I'm making a Server with a database inside, but while I'm loading the main JFrame and while I'm connecting to the database reading username & password from a .properties file I chosed to let the user know that the program is running, what the program is doing in that specific moment, and also let him create a .properties file if it not exists (first launch).
The problem is that I need to create 2 jframes, 1 that shows the launch progress, and 1 that appears only when user needs to create a .properties file: the problem is that I have to pause the first one while the second is running, and restart running the first while the second is closed performing all actions; I made it in two ways, but it didn't work: first, I tried inserting a wait() call opening the second JFrame and a notify() call while closing it; second, I tried using threads, but the problem is that the thread that I stop doesn't start when it should... here's some code:
jFrame1.setBounds(0,0,500,500);
this.setVisible(true);
jProgressBar2.setValue(0);
prop = new Properties();
jTextArea1.setText(jTextArea1.getText()+"Searching file config.properties... \n");
try {
FileReader fr = new FileReader("config.properties");
jProgressBar2.setValue(33);
jLabel3.setText("33");
jTextArea1.setText(jTextArea1.getText()+"File config.properties found... \n");
} catch (FileNotFoundException ex) {
jFrame1.setVisible(true);
jTextArea1.setText(jTextArea1.getText()+"File config.properties not found... \n");
}
I want to pause while I ented the "catch" section; "this" is the first JFrame, "jFrame1" is the second one.
Some hints/tips?
Solution: don't use multiple JFrames. Make the window that's acting as a modal dialog not a second JFrame, but rather a real modal JDialog.
We should probably close this question as a duplicate as this exact same question gets asked again and again.
Related
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 would like to exit a console application while a javax.swing.JFrame still exists.
I have a console program that displays a javax.swing.JFrame. Sometimes I want to redirect the standard output to a file.
java -cp path com.domain.package > output.log
One plausible JFrame config value is WindowConstants.DISPOSE_ON_CLOSE and it is my understanding that the JFrame becomes disposed of when it is clicked to close, but the console program blocks at the closing brace of main. I do not know what it is waiting for. At that point I have to Control-C to terminate main.
Another plausible JFrame config value is WindowConstants.EXIT_ON_CLOSE and it is my understanding that when the JFrame is clicked to close, not only does the JFrame close but it also causes main to terminate. Note that even if main has reached the closing brace it does not exit until the click that closes the JFrame. This behaviour is better than the previous case because there is no need to Control-C to terminate main.
I want the console program to terminate so that the output.log file is released even if the JFrame is still alive. I tried to do this by having the JFrame owned by a Runnable in a Thread. That did not work; the console program does not terminate until the JFrame is closed.
// main program...
static void main(String[] args)
{
PlotWorker worker = new PlotWorker(data);
Thread thread = new Thread(worker);
thread.start();
// do not use thread.join
// simply exit at the closing brace of main
}
// owner of the JFrame...
class PlotWorker implements Runnable
{
JFrame jFrame;
#Override
public void run()
{
jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Realistically I know I can look at the output.log file with a text editor (or just Linux cat the file from a second console) even if the standard output in the first console still has a "handle" on the output.log. I would prefer a clean solution that exits while the JFrame still exists.
EDIT: This question is no longer important to me. I decided to screen capture and save to disk the JFrame image, thereby obviating the need to keep the JFrame open, then proceed to close the JFrame, thereby closing all files.
EXIT_ON_CLOSE and DISPOSE_ON_CLOSE to my knowledge only govern the application behavior in regards to what happens with the JFrame, I.E. if it's set to exit_on_close, you get a System.exit(0) when the JFrame is closed.
In general, I think System.exit(status) is what you want when terminating your application, this should dispose of any object created by it, release file-locks and close any windows. Might be a little messy if you're using a stream to write to your logfile because that will be terminated too, possibly without calling it's .close() function.
This question already has answers here:
java thread.sleep puts swing ui to sleep too
(3 answers)
Swing - Thread.sleep() stop JTextField.setText() working [duplicate]
(3 answers)
Closed 4 years ago.
I'm working on a game project where I'm creating a GUI using JSwing. It looks something like this:
A lonely 'F'
I'm trying to create a 'typewriter' effect, and so have a Thread.sleep(100) in my custom PrintUtils method (let's call it printToGui). I've routed System.out to the TextArea in the center of the GUI, and the first time I run the program the 'typewriter' effect works great and the startup text I send through printToGui shows up as it should. However, whenever I click a button (which triggers more text getting sent through printToGui), the app freezes, and won't unfreeze until the length of time it would have taken to print with Thread.sleep() finishes, spitting out all the text at once.
What I've figured out is that the first time I start the app, Thread.sleep() is happening on the "main" thread, while every time I click a button it's happening on the AWT-EventQueue-0 thread. I assume this is the problem, but maybe it's not; how do I get future output to the GUI to happen on the "main" thread and not the new one? Thanks!
I am trying to create a chat client for a program of mine and I would like to open a new window for each chat (A & B will not be in the same window as A & C) I have psudocode for what I am trying to do but unsure on how to write it.
Chat client:
inputstream.read()
Read who message from
If (chat window arleady open with person from)
{
Add Message to output section of the window
{
else if (chat window not open)
{
Open new chat window with person from
Display message in new chat window
}
To do this, the thing I have thought about is storing the IPs in an array and then whenever the client gets a message it would look through the array to see if the IP was stored. If it is stored, the window should already be open, otherwise the window needs to be opened. I can program this by using the defaultonclose command from JFrame to just call a removal of the IP when the window is closed, but here are the problems I am running into.
Once I search the array for the IP addresses, If the window is already open (say I have A B and C talking to D) how do I insure if C sends a message that it gets placed in the C window?
1.1 I have thought about spawning a new thread, naming the thread, and then when a message comes in pass it into the the thread that matches the name, but I am not sure about how to do that. I have read the names of threads before but never passed something into a specific thread.
Is there anyway to do this easier without downloading extra libs?
don't use JFrame for another window, because you can't to set parent v.s.owner, use JDialog instead
then JFrame.getOwnedWindows() returns all instances of JDialog(s) where is used JDialog(myFrame owner)
in all cases Window[] allWindows = Window.getWindows(); returns all instances from current JVM, returns all instances of (J)Frames, (J)Dialogs, (J)Windows or JOptionsPanes
In a package in Netbeans I created two JFrame Forms, first one is Login, second is, mainProgram, after the successful log in, I use the following way to "close" the Login frame and open the main program frame.
mainProgram m=new mainProgram();
m.setVisible(true);
setVisible(false); //to hide the log in frame
Is this the correct way? Isn't it wrong if these two separated classes are hidden instead of being closed? are these one process or two different processes? if there's a better way then what is it?
thanks..
Is this the correct way?
Yes, this should be fine.
isn't it wrong if these 2 separated classes are hidden instead of
being closed?
The ideal is dispose of your unused forms (such as the login form when not needed any more)
are these 1 process or 2 different processes?
These will run on the same process
In a package in Netbeans I created 2 JFrame Forms, first one is Login, second is, mainProgram, after the successful log in, I use the following way to "close" the Login frame and open the main program frame.
use CardLayout, after correct login you can to switch the GUI to next Card and/or with change for JFrame Dimmnsion on the screen too,
in my opinion the more correct way is to use another class, like Launcher, which will have the entry point (main method).
Make the login window as a modal JDialog, and set DISPOSE_ON_CLOSE as a value of default close operation. The class of dialog should contain a method to inform a user really logged in. After the login dialog is closed, show the main frame
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn())
mainFrame.setVisible(true);
Try this...
The approach you used to hide and un-hide is fine, but will be better if dispose is used.
Try applying the Singleton pattern on the classes which govern these JFrames.
And yes they both will be on the same Process.