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!
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.
This question already has answers here:
Will Runnables block the UI thread?
(4 answers)
How to update swing GUI from inside a long method?
(3 answers)
Closed 3 years ago.
I'm facing a strange behavior from the Java Runtime(VM) when I'm trying to display a label or progress bar on the screen when something happens.
The scenario is like this:
the user will press a button to do a certain action
this action is a kind of process on the DB which could take some seconds
I'm displaying a message in a Jlabel field which is already in the form but set to be invisible when the form opens.
Then when the user presses a button I'm setting this label to be visible and do some processing and then set it back again invisible as it was, which is very simple logic.
problem is the Jlable is displayed after the processing is done and not before.
The same problem with happens also a progress bar.
Any explanation why is this happening?
here a sample of the code
Mylable.setVisible(false); defaullt status when the form opens
Event Occurend (user clicked a button)
Mylable.setVisible(true);
....... do some process here
Mylable.setVisible(false);
This question already has answers here:
Splash screen in Android Application
(3 answers)
Closed 8 years ago.
In my app, there are some time-taking processes in the onCreate method. Right now, the user sees a black screen until the data is loaded and is ready to be displayed. How can I add some sort of splash screen that says "Data is Loading" while the processes take place?
Thanks
EDIT : I tried putting setContentView(R.layout.splash_layout) at the start of onCreate but it had no effect.
Create splash activity with some sort of image in layout background. Here in onResume start AsyncTask or just thread to do your time consumable operation. When task would be finished just start your "Main" activity.
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.
This question already has an answer here:
Loop doesn't see value changed by other thread without a print statement
(1 answer)
Closed 7 years ago.
I am using the javax.swing packages to construct a gui, and have a while loop running forever with an if statement inside, to see if a button has been pressed. For some reason unbeknownst to me, this code only works if I print to the console inside the while loop.
Here is the algorithm structure:
while(true){
System.out.println(" ");
if (startOver && playPressed) {//set to true on JButton press
//do stuff
}
}
Possibly this is some sort of threading issue? Has anyone ever encountered such a problem before? Is there a method of waiting for a JButton to be pressed that doesn't involve an infinite while loop?
Thanks in advance!
Swing is event-based. You're not supposed to have infinite loops waiting for a button to be pressed. The loop is implemented by Swing internally. What you're supposed to do is to add an action listener to the event, which will be called by the button when it's clicked:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("The button has been clicked!");
// do stuff
}
}
This is fundamental stuff when dealing with Swing. You should read the swing tutorial.
Any infinite loop in the swing event dispatch thread will freeze the GUI forever.
The only way I was able to overcome this problem without an infinite loop was by creating a new thread for the "//do stuff" portion of the algorithm.
very strange, and I still don't understand why I had to print to console to make it work within the while loop.