简体   繁体   中英

Enabling/disabling a JButton by another JButton

I've got JButtons "Pause" and "Unpause". When a user pauses the program, the Pause button should be disabled and the Unpause button should be enabled. I don't know how to write it. The unpause button works, but the Pause button doesn't, because "unpause cannot be resolved". How to deal with it? There's my code:

final JButton pause = new JButton("Pause");

    pause.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Url.pauseThread();
                pause.setEnabled(false); //this works
                unpause.setEnabled(true); //this does NOT work - "not resolved"

            } catch (InterruptedException e1) {

                e1.printStackTrace();
            }  

        }
    });

    final JButton unpause = new JButton("Unpause");

    unpause.addActionListener (new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Url.resumeThread();
                pause.setEnabled(true); // this works
                unpause.setEnabled(false); // this works
            } catch (InterruptedException e1) {

                e1.printStackTrace();
            }
        }
    });

Declare pause and unpause button and then add listeners.

final JButton pause = new JButton("Pause");
final JButton unpause = new JButton("Unpause");
    pause.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Url.pauseThread();
                pause.setEnabled(false); //this works
                unpause.setEnabled(true); //this does NOT work - "not resolved"

            } catch (InterruptedException e1) {

                e1.printStackTrace();
            }  

        }
    });



    unpause.addActionListener (new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Url.resumeThread();
                pause.setEnabled(true); // this works
                unpause.setEnabled(false); // this works
            } catch (InterruptedException e1) {

                e1.printStackTrace();
            }
        }
    });

Basically, you were calling setEnabled from unpause button in pause button listener before unpause button was even declared.

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