First of all I'm new to Java and you'll probably be able to guess. Thanks in advance.
I'm currently writing a board game using Java for an assignment. There are human and computer player classes, and the GUI only in the human player class. In the human class I use a class called 'UI' extending JFrame where the user selects a piece.
At the moment this UI class waits for the enter button to be pressed then sets a 'done' variable to true. In the human player class I create this UI then wait in a while loop continuously checking this boolean before getting the X/Y position of the move.
while (!input.moveEntered());
move.setPosition(input.getX(), input.getY());
This only seems to work if the while loop is not empty. If I add a print statement in there it works fine.
It seems like there is a much better way to go about this. I've looked into dialogs but I don't close the window every time a move is entered.
Thanks for reading.
You should never be busy-waiting; in your case, I would show a modal JDialog. When the user has entered their input, the setVisible(true) method will end without busy-waiting.
Or maybe I misunderstood your problem and you only need to define an event listener in your main JFrame in order to handle user input. Have a look at
http://www.tutorialspoint.com/swing/swing_event_listeners.htm
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 am coding a program whose functions include one that checks whether the user input is one of the arrow keys and moves an on-screen sprite accordingly.
I am using the KeyListener interface for an inner class I call ArrowListener. Currently, I have code in the keyPressed() that moves the sprite on the screen.
I am wondering how often my ArrowListener class checks for keyboard input, because I have another method in the larger component class that calls repaint() every 100 milliseconds. If the KeyListener class checks user input more or less often than this, I will change the repaint frequency as well.
EDIT:
I realized that KeyListener doesn't check/poll the keyboard for inputs regularly, but processes interrupts from the keyboard. Still, if I were to hold down a key on the keyboard for, say, 5 seconds, how many interrupts would KeyListener process?
It looks like I was mistaken; what you're looking for are KeyBindings; these allow you to execute an ActionListener only once when a key is pressed.
I'm building a Swing game that is drawn entirely (everything, menus included) in single JPanel object. I have a game loop in this JPanel, which handles everything from updating the state of the game to drawing it and so on.
Now, I need to somehow enable the player to type in their own text in some of the menus. Creating a new player profile, saving some other information and the like. I can't seem to find a good way for doing this. Using a Scanner is obviously out of the question, since doing that will interrupt the event dispatching thread, freezing the game on the spot (I learned that the hard way).
I have concluded that the only way to do this is to use the KeyListener to somehow record the keys I have pressed on the keyboard. I have been experimenting with its keyTyped method, but my results have been poor. I have been able to make it record my keypresses, but the problem is, it records EVERY key I have pressed, including backspace, control, TAB, and so on... Plus, every character that I type is outputted capitalized, regardless of whether I have Caps Lock on or not.
I hope you understand what I'm trying to achieve here. So my real question: Is there any easy way to record typing using KeyListener? Or is there some other way that can be used inside of the event dispatching thread?
Your options are:
Use a standard popup dialog and get your text that way
Embed a text field into your panel to receive input
The problem is that a KeyListener is just that, it listens for key events. The standard text input components combine this with a DocumentListener for processing text
I am currently learning java and wanted to give myself a project that was both challenging and fun. I decided to build a game that I remember playing when I was a kid called dopewars.
This is my second attempt at this game. When I began my first attempt, all went well. After a short while my source code began to fill wildly out of control until I could continue no more as I kept getting lost within mountains of code.
I then decided to begin again, only this time I wanted to seperate the gui from the logic (2 different .java files). This is where my problem lies. Previously this would work fine. Since seperating my java files the functionality has stopped.
When I press jbutton b1, my program is supposed to take the price value of cocaine and the units value entered into the jtextfield by the user, perform a calculation by accessing a method within Buy.java, and then update the appropriate JLabels within the s jpanel of GUI.java.
For example, user x wants to buy cocaine at the price indicated, so he enters a value representing the quantity he would like. He then presses the buy button which ultimately deducts the money from his pocket which is shown on the left side of the program window by using a method within the Buy class.
I hope you can understand my explanation and I hope to hear from you soon. Thanks.in advance. My Source code is below.
Maybe you should make a main.java (with GUI, etc.) and a logic.java (or whatever you want to call it) and make the main class Extend the logic class. to solve your jbutton problem, you should probably make the Main class extend the JFrame class, and implement the ActionListener interface, and then in the ActionPreformed method, call a method to do the logic from the logic class. I hope this helped.
I'm building a game using Java for a university project. The game had to use a textual interface at first, and only later we had to add a GUI.
I have a thread running the game logic and updating the game model, and a separate thread, the one with the main function, having the JFrame instantiated on, where I then switch panels according to the game state (the controller tells the gui which frame to display with a setPage method).
Getting the user input, however, is what is driving me crazy now.
With the textual interface, all I had to do to get the user input was to call a method, something like getPlayerNum, and after the user put in the number and pressed enter I would have the input back to the controller.
All the game logic is implemented in a game loop, asking for input when it needs it and notifying the output to the view.
How can I emulate a similar behavior now that I'm forced to use a event-based gui?
How can I block the method call until the user clicks a button, and then have the method return the correct value?
Kudos for developing an independent game model. As a prelude to designing your GUI, start with this very simple game. Add a TextView that listens to the model and reports on game progress. This will help you see how the GUI works, and it may help you decide what additional features you may need in your model.