Trying to wait for a button press on a seperate JFrame- problems.

Hi,
I've been getting aquainted with Java recently. I'd like to think I was reasonable now at creating console based applications but I'm having a lot of trouble getting used to the swing API. I'm making a little game type thing at the moment and part of it involves displaying a problem to the user in a seperate JFrame and returning which option they picked. If I was doing this in a console based App I'd probably do something along the lines of:
     while (UserInput == null) { //while they haven't entered anything continue to loop.
          UserInput = InputScanner.next(); //get the user's input
     }I thought I'd do something similar for my JFrame based app but haven't been able to do it. I essentially would like the code to not execute past a certain point until one of the options on the JFrame has been picked. Here's the code for the JFrame showing the dilemma to the user:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
* This is the window displayed to a user with dilemma details
public class DilemmaWindow extends JFrame implements ActionListener {
    int OptionPicked = 0; //the option the user picks
    JLabel DescriptionLabel;
    JButton Button1;
    JButton Button2;
    public DilemmaWindow(String WindowTitle, String LabelText, String Button1Text, String Button2Text) {
        //construct the JFrame with the relevant parameters
        setTitle(WindowTitle);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.CENTER));
        Button1 = new JButton(Button1Text);
        Button2 = new JButton(Button2Text);
        Button1.addActionListener(this);
        Button2.addActionListener(this);
        DescriptionLabel = new JLabel();
        DescriptionLabel.setText(LabelText);
        add(DescriptionLabel);
        add(Button1);
        add(Button2);
        pack();
        setVisible(true);
    public void actionPerformed(ActionEvent evt) {
        //determine which button was clicked and set OptionPicked accordingly
        if(evt.getSource() == Button1) {
            OptionPicked = 1;
        } else {
            OptionPicked = 2;
    public int GetDilemmaChoice() {
        if (OptionPicked > 0) { //if an option was picked
        this.dispose(); //clean up the window
        return OptionPicked; //return which option was picked
}The idea of this being that it constructs a window and when the GetDilemmaChoice() function is called it'll return which button has been clicked.
I do, as I said, want to wait until one of the buttons has been clicked before continuing with the execution of the code in the class that constructs the JFrame, so I made the following function:
public int GetDilemmaChoice() {
        int Choice = 0;
        DilemmaWindow MyDilemmaWindow = new DilemmaWindow(CaperDilemma.GetDilemmaName(),CaperDilemma.GetDilemmaDescription(),CaperDilemma.GetOption1Text(),CaperDilemma.GetOption2Text());
        while (Choice == 0) {
            Choice = MyDilemmaWindow.GetDilemmaChoice();      
        return Choice;
    }The idea being that while the window returns that no buttons have been clicked the function loops round. The problem I'm having is that the while loop continually looping seems to hog all the CPU time or something, as the dilemma JFrame doesn't display properly (I get a blank window, with none of the buttons) and so I can't click any of the options. I've been banging my head against a brick wall all day trying to get round this and am wondering if I should put the looping in a seperate thread or something. Sadly, though, I don't know anything about threads so wouldn't know where to start.
If anyone has any idea of how to solve this problem I'd be very grateful! I hope I've managed to explain it well enough.

Why not use a modal JDialog here and not a JFrame. You probably shouldn't be coding directly to a JFrame (or JDialog) anyway but to a JPanel that can be placed on the proper root container of choice (which again here is a JDialog). You can make your JPanel as complex as desired, then place it in the JDialog, make that dialog application modal, and when you show it via setVisible(true), the application will halt at that point until the dialog has been dealt with.

Similar Messages

  • Wait For A Button Press

    Hey, I am currently creating a game and need to know how to wait for a certain button to be pressed. A popup message comes up that tells the user to press a button, then I need to wait for the button to be pressed. Then once the button is pressed, I want another message to come up. The problem is, I have no idea how to wait for a button press after the first message comes up. Instead it just displays the first message, then the second directly after.
    Thanks

    So you have a button that is always present. Normally clicking the button does nothing. But sometimes a message shows up, in which case if the user clicks the button, something happens. Right?
    UI principles aside (it's bad form to display a button that does nothing), this is pretty simple.
    Create a field to track whether the button does anything. For example:
    private boolean buttonActive = false;In your action listener for that button, first check the value:
    public void actionPerformed(ActionEvent e) {
        if (buttonActive) {
            // do your thing
    }If the buttonActive is true, it does something, otherwise it does nothing.
    After you display the message, set buttonActive to true. When you want the button to become a brick again, set it to false.

  • Wait for a button click

    Hi,
    Here's the problem :
    my main class calls :
    LoginContext loginContext = new LoginContext("Main",
    new DialogCallbackHandler());
    I've made a DialogCallbackHandler class which opens a JFrame with 2 fields (TextField & PasswordField) and a button "ok".
    But the LoginContext wants immediately an answer (the login & the password). How can I make the loginContext waiting for the button click.
    I tried with a
    while(!buttonClicked);
    but it's not a good solution.
    I also tried with a Thread inside this loop while and sleeps (during a 500 ms). But I think there's a better solution...
    Can I make a wait, and a notify for this or not.
    Thank you for your help.
    Yann
    -- http://www.objectweb.org/jonas

    Why don't you use the JOptionPane class.
    I think it provides all that you need.
    For example use the method :
         String pass = "azedvge";
         JPasswordField passwordField = new JPasswordField(20);
         int result = JOptionPane.showConfirmDialog(parentComponent, password, "Password check", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
         if (result == JOptionPane.OK_OPTION) {
              String p = new String(passwordField.getPassword());
              if (p.equals(pass)) {
                   // OK !
              else {
                   System.exit(0);
         else {
              System.exit(0);
    I hope this helps,
    Denis

  • HT201406 I cannot get my touchscreen to work not even able to slide to turn on. tried resetting, waited for the apple and then the usb itunes disc/music note appeared then nothing.. is this ipod junk?

    I cannot get my ipod touch touchscreen to wrok not even able to slide to turn on. Ive tried resetting, waited for the applie.. long wait then the USB plug appeared wit Itunes disc/music note then it just stayed there.. is this ipod junk?

    Try:
    - Reset the iOS device. Nothing will be lost
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Restore from backup. See:
    iOS: How to back up
    - Restore to factory settings/new iOS device.
    iOS: How to back up your data and set up as a new device
    - Make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar

  • Wait for user to press ok in JFrame

    I have two windows the main one is for setting configuration values.
    the second is for one of the config values that is a list and i have made a JFrame that has the list and can remove and add things to it.
    it also has a OK button for when the user has finished and a function to convert the list into a string i can store in my config file.
    what i dont know how to do is make the main window wait until OK is press on the second window
    then it needs to get the string with the list in it.
    if you have some code or a tutorial you could point me towards that would be great.
    Scott.

    1) don't use a second JFrame, use a modal JDialog as this is precisely what it is built to do.
    2) Have the class that produces the JDialog's components also have a public getter method(s) to extract what you want from the dialog once it has been closed.
    3) Search the forum for examples. you'll find lots, many helpful.

  • Delete Record Behavior doesn't wait for Submit button

    I have master / detail page set.  From the detail set there are links to delete or update a record.  When I click the link to delete the record, it goes to the   confirmation page with the correct record.  Now, when I add the delete record server behavior and a submit button, this is what happens.  As soon as I click the link to go to the delete confirm page, the record deletes and the page redirects to the page I put in the server behavior.  It doesn't show the confirm page and doesn't wait for me to hit the confirm button.  The page runs and successfully deletes the page from the DB.
    How do I get it to wait until I hit the submit button?

    You need to surround your delete query with an "If" statement that checks for a confirmation variable of some sort, then when the user clicks the confirmation link you can pass the necessary variable and the ID of the record the delete query is expecting.
    As an alternative you could use a JS alert fuction to ask the user if they are sure they want to delete the record and then allwo the delet to run after confirmation. To do this you could use code like this...
    <input type="submit" name="DELETE" value="DELETE"
       onclick="return confirm('Are you SURE you want to DELETE this record?')">
    Lawrence   *Adobe Community Expert*
    www.Cartweaver.com
    Complete Shopping Cart Application for
    Dreamweaver, available in ASP, PHP and CF
    www.twitter.com/LawrenceCramer

  • Dynamic Action with KeyCode check for ENTER button pressed

    Hi,
    I want to create a dynamic action which executes if the ENTER button of field P1_NAME is pressed.
    I thought about this type of DA:
    Event: Key Press
    Selection Type: Item(s)
    Item(s): P1_NAME
    Condition: Javascript expression
    Value: this.triggeringElement.keyCode == 13
    That unfortunately doesn't work! Dynamic action doesn't get executed...
    Hope for help! :)
    Tobias

    I found the solution in my own blog: :)
    Event: Key Press
    Selection Type: Item(s)
    Item(s): P1_NAME
    Condition: Javascript expression
    Value: this.browserEvent.keyCode == 13

  • Captivate 8 - I want my slides to stop at the end and wait for a button click to advance

    It works when published as HTML5, but NOT as swf.
    (I have those specific slides set to pause at the end.  They contain stuff the user might want to write down.)
    Instead, the swf project advances to the next slide and THEN stops.  Instead of using the forward button, the user has to use the play button on the skin.
    Any help would be greatly appreciated!

    I suppose you used the On Exit event to pause? In that case the SWF-behavior is normal behavior: the action occurs only after exiting the slide, so Pause will be on first frame of next slide.
    Why not add a click box, time it for the rest of the slide and it will pause at the last frame. And you talk about a Forward button? Why not use the pausing of that button to pause at the last frame (or almost at the last frame)?

  • IPad mini and itouch storage filling up daily problem...similar to many post but only fix is restart and last about 1 day and fills up with "other" no new downloads very few apps...waiting for software fix since so many having same problem. Help

    Similar to many others storage mystically filling up everyday with nothing new being put on. Only solution is to testers ipad then get totally free storage until later that day or next day. Hoping for a software fix.

    How much space is used by your Other? You may be able to reduce.
    How Do I Get Rid Of The “Other” Data Stored On My iPad Or iPhone?
    http://tinyurl.com/85w6xwn
    How to Remove “Other” Data from iPhone, iPad and iPod Touch
    http://www.igeeksblog.com/how-to-remove-other-data-from-iphone/
    With an iOS device, the “Other” space in iTunes is used to store things like documents, settings, caches, and a few other important items. If you sync lots of documents to apps like GoodReader, DropCopy, or anything else that reads external files, your storage use can skyrocket. With iOS 5/6/7, you can see exactly which applications are taking up the most space. Just head to Settings > General > Usage, and tap the button labeled Show All Apps. The storage section will show you the app and how much storage space it is taking up. Tap on the app name to get a description of the additional storage space being used by the app’s documents and data. You can remove the storage-hogging application and all of its data directly from this screen, or manually remove the data by opening the app. Some applications, especially those designed by Apple, will allow you to remove stored data by swiping from left to right on the item to reveal a Delete button.
    What is “Other” and What Can I Do About It?
    https://discussions.apple.com/docs/DOC-5142
    iPhone or iPad Ran Out of Storage Space? Here’s How to Make Space Available Quickly
    http://osxdaily.com/2012/06/02/iphone-ipad-ran-out-of-available-storage-space-ho w-to-fix-quick/
    6 Tips to Free Up Tons of Storage Space on iPad, iPhone, and iPod Touch
    http://osxdaily.com/2012/04/24/6-tips-free-up-storage-space-ipad-iphone-ipod-tou ch/
    Also,
    How to Clear Message/iMessage Cache on iPhone & iPad And Reclaim Lots of Free Space
    http://www.igeeksblog.com/how-to-clear-message-imessage-cache-on-iphone-ipad/
    What is Stored in iCloud and What is Not
    https://sites.google.com/site/appleclubfhs/support/advice-and-articles/what-is-s tored-in-icloud
     Cheers, Tom

  • Waiting for activation I message who has the same problem? How can I fix?

    Brand new iPhone 5 not activating FaceTime or imessage

    Are these old files that you edited in CS6 and then just saved (instead of save as)?

  • Touch Events: How can I check for a button being pressed while another button is being held down?

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

  • Switching Frames (cardsLayout), doing something, waiting for button

    Hi,
    I am switching JFrames in my application and each frame is to call a specific function and then wait for a button click.
    so the code would be:
    function(){
            cardsLayout.show();
            doSomeCalculations();
            waitForButtonClick
            continueWithSomething //depending on which Button was clicked
    }My problem is, how to realize the waitForButtonClick?
    What would you suggest? I have heard about synchronize. Is this the way to go, or is there an easier/better way?
    Besides a while(notClicked) way ;-)
    Thanks!

    pir wrote:
    it is not that I do not want to learn Java. Please understand that Java is not with what I am earning my living, it is a tool for me, to make some task easier, which I would have otherwise have to do step by step by hand. I will never be as good as someone who spends his time with Java every day. I also have only a specific task to perform in a given time, so I need only specific information - which I am definitely willing to learn - and not all there is about Java and Swing.You must understand that at its core, your question is not about anything specific but rather it boils down to: "how to create an event driven program in Swing".
    The only reasonable answer to this is to send you to the Swing tutorials where, if you have the interest, ability, and inclination, you can learn the tools needed to do Swing and event programming. If you choose not to do this, no one in this forum can help you. Period.
    I hope this clarifies the situation enough, to allow someone to have a heart and point me in the right specific direction, even knowing that I might use this knowledge only once.And once again, I recommend that you hit the Sun Swing tutorials and start learning. Accept this and follow this recommendation and you will find success. If not, well,... it's your choice.
    Thank you in advance for any specific help.This is as specific as it's going to get at this stage. Much luck.

  • Text Entry not waiting for entry before continuing

    Captivate 4
    I'm trying to add a TEB where the user will need to enter the correct text before moving to the next slide.  I would like it to continue as soon as they user types the correct entry.  The problem is that the slide doesn't pause to wait for the entry - it continues to the next slide without anything being typed or a click.  ??
    I have the correct text listed in the 'Correct Entries' box and have it set to 'go to next slide' for 'On success'.  Under 'Options', I have it set to 'Validate User Input'.  I do not have any hint or caption buttons, and I am not showing a 'submit' button.
    Can someone tell me how to get it to pause the training to wait for the user to enter the correct text?
    Screen shots below.
    Thanks in advance,
    D

    Hi there
    Indeed there is!
    You enable the Button in the properties. This will place an associated button next to the field.
    What's that you are asking? You don't want a button?
    Well, nobody said you actually have to SEE the button! Just double-click the button and its properties will show. Choose Transparent Button and configure it so it's invisible. Then you configure the other "1" for the Button press!
    Cheers... Rick
    Helpful and Handy Links
    Captivate Wish Form/Bug Reporting Form
    Adobe Certified Captivate Training
    SorcerStone Blog
    Captivate eBooks

  • Sending an object from client to server always on button press

    What I need is to send an object from client to server but I need to make server wait until another object is sent. What I have is the JFrame where you put the wanted name and surname, then you create a User object with these details and on button press you send this object to the server. I just can't hold the connection because when I send the first object, server doesn't wait for another button click and throws EOFexception. Creating the while loop isn't helpfull as well because it keeps sending the same object again and again. The code is here
    public class ClientFrame extends JFrame {
        private JButton btnSend;
        private JTextField txfName;
        private JTextField txfSurname;
        public ClientFrame() {
            this.setTitle(".. ");
            Container con = this.getContentPane();
            con.setLayout(new BorderLayout());
            txfName = new JTextField("name");
            txfSurname = new JTextField("surname");
            btnSend = new JButton(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SSLSocketFactory f =
                            (SSLSocketFactory) SSLSocketFactory.getDefault();
                    try {
                        SSLSocket c =
                                (SSLSocket) f.createSocket("localhost", 8888);
                        c.startHandshake();
                        OutputStream os = c.getOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(os);
                        InputStream is = c.getInputStream();
                        ObjectInputStream ois = new ObjectInputStream(is);
                        boolean done = false;
                        while (!done) {
                            String first = txfName.getText();
                            String last = txfSurname.getText();
                            User u = new User();
                            u.setFirstName(first);
                            u.setLastName(last);
                            oos.reset();
                            oos.writeObject(u);
                            String str = (String) ois.readObject();
                            if (str.equals("rcvdOK")) {
                                System.out.println("received on the server side");
                            } else if (str.equals("ERROR")) {
                                System.out.println("ERROR");
                        //oos.writeObject(confirmString);
                        oos.close();
                        os.close();
                        c.close();
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(ClientFrame.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        System.err.println(ex.toString());
            btnSend.setText("send object");
            con.add(btnSend, BorderLayout.PAGE_START);
            con.add(txfName, BorderLayout.CENTER);
            con.add(txfSurname, BorderLayout.PAGE_END);
            this.pack();
            setSize(200, 150);
            setVisible(true);
    public class TestServer {
        public static void main(String[] args) {
            try {
                KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(new FileInputStream(ksName), ksPass);
                KeyManagerFactory kmf =
                        KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, ctPass);
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(kmf.getKeyManagers(), null, null);
                SSLServerSocketFactory ssf = sc.getServerSocketFactory();
                SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8888);
                printServerSocketInfo(s);
                SSLSocket c = (SSLSocket) s.accept();
                InputStream is = c.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);
                OutputStream os = c.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);
                boolean done = false;
                User u;
                  while(!done){
                    u = (User) ois.readObject();
                    String confirmString = "rcvdOK";
                    String errorString = "ERROR";
                    if (u != null) {
                        System.out.println(u.getFirstName() + " " + u.getLastName());
                        oos.writeObject(confirmString);
                    } else if (u == null) {
                        oos.writeObject(errorString);
                is.close();
                s.close();
                c.close();
            } catch (Exception e) {
                    System.err.println(e.toString());
    }Thanks for any help, btw this doesnt need to be via ssl, the problem would be the same using only http. Please anyone help me:)
    Edited by: Vencicek on 7.5.2012 2:19
    Edited by: EJP on 7/05/2012 19:53
    Edited by: Vencicek on 7.5.2012 3:36

    Current code fails because it's sending still the same entity again(using while loop)No it's not. You are creating a new User object every time around the loop.
    which makes the system freezeWhich means that you are executing network code in the event thread. Don't do that, use a separate thread. At the moment you're doing all that sending inside the constructor for ClientFrame which is an even worse idea: you can never get out of there to the rest of your client program. This is a program design problem, not a networking problem.
    and doesn't allow me to set new parameters of the new entityI do not understand.
    I need to find a way to keep Server running even when the client doesn't send any data and wait until the client doesnt press the send button again to read a new object.That's exactly what happens. readObject() blocks until data is received.

  • Waiting for many threads

    Hey guys,
    I know how to make one thread wait for another named thread to complete, but how do u make a thread wait for many threads to complete with the added problem of not knowing the names of the threads your waiting for? Looked and been trying for ages but can't get anything to work.
    Thanx
    Lisa

    No i saw it, pehaps i should rephrase with a question, how would you go about giving all these threads a reference? If it ain't obvious already am not great with java and if someone could tell me how to give the threads spawned references it would be great.
    As ive explained the code is really long so am not going to waist peoples time by posting it. Here is basically how i am spawning the threads "willy-nilly" style.
         while ((p < searchTerms.size())&&(p < 30)){
             term = (searchTerms.elementAt(p)).toString();
             NetChecker nc = new NetChecker(term,excludedAdds,refWeb);
             searchClasses.addElement(nc);     
             new Thread(nc).start();
             p++;
         } the classes all return web addresses in a vector, thats why i need all the threads to complete so i can collect all the results
    Thanx
    Lisa

Maybe you are looking for