Advertisement

Jframe and events

Started by September 19, 2014 12:06 AM
2 comments, last by BUCH Dragon 10 years, 4 months ago

I'm working on a project, which so far I've only taken a java class and have learned how to use the Console and a little about Jframe.

It's text base adventure type thing within a Jframe using multiple text fields however I don't know how to take in inputs like when using the scanner when using the console. I understand Action listeners and using key listeners but I'm not understanding how to get the program to wait on input like it would with the console and scanning. I've done some research and I have seen the term latch come up a few times. Do I want to use latches? I thought latches were mainly for running something, and to my knowledge I don't think I'd have to run?

Are you using Swing and the JTextField components? If so you need to add listeners to them to detect user interaction. This is nothing like getting input from the console. It is a completely different method.

Checkout the Java tutorials. http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

Advertisement

Well what I want is some magic method that holds the program from going on to the next step. But now that I think about it, my plan is achievable, to my knowledge, by putting just about everything in the action listener along with tons of loops. Which doesn't sound that great to be honest. I'm still not sure if it would be going about the right way though, if using run and some trick with that would work better? Like putting a sleep on something for 10000000 seconds and if the user inputs something then change that time to 0. I'm not that knowledgeable on run though, it's kinda on the to do list.

You might want to research a bit on the wait() and notify() methods(here is a hint).

An alternative method is to make a short "sleep loop" checking for a condition to become true, like so:


        // Sleep until the socket is created or re-opened.
        try
        {
            while(socket == null || socket.isClosed()) Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

in this case if a socket is created or an existing one closed, this loop would "pass through".

You could also set that 100ms sleep to be shorter if the action should be checked for more frequently, or make a really long sleep and interrupt that Thread from another Thread.

This topic is closed to new replies.

Advertisement