简体   繁体   中英

Java swing wait for button click

How do i add wait for jButton1 to be click to continue?

I have this code:

while (gameStatus == Status.CONTINUE){
    ////here add wait for jButton1 click  
    sumOfDice = rollDice(); // roll dice again
}

i have done this but its not working:

        while (gameStatus == Status.CONTINUE) { 

        jButton1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e, int sumOfDice) {
                sumOfDice = rollDice();

            }
        });

You're confusing linear command line programming with event-driven GUI programming, and that won't work. Instead of waiting as you're doing, you need to respond to events as they occur, and how you respond will depend on the state of your program (actually the state of your model).

Note that this won't compile:

    jButton1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e, int sumOfDice) {
            sumOfDice = rollDice();

        }
    });

since actionPerformed is an overridden method and only can take one parameter

Better would be something along the lines of:

    jButton1.addActionListener(new ActionListener() {
        private int sumOfDice = 0;

        @Override // don't forget this important annotation
        public void actionPerformed(ActionEvent e) {
            if (gameStatus == Status.CONTINUE) {
               sumOfDice = rollDice();
            }
        }
    });

For a more detailed and specific answer, consider posting more detail about your problem along with relevant code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM