另一个JButton启用/禁用JButton

时间:2013-08-21 22:20:11

标签: java swing jbutton

我有JButtons“Pause”和“Unpause”。当用户暂停程序时,应禁用“暂停”按钮并启用“取消暂停”按钮。我不知道怎么写。 “取消暂停”按钮有效,但“暂停”按钮不起作用,因为“取消暂停无法解决”。怎么处理呢?这是我的代码:

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();
            }
        }
    });

1 个答案:

答案 0 :(得分:2)

声明暂停和取消暂停按钮,然后添加侦听器。

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();
            }
        }
    });

基本上,您在暂停按钮监听器中从取消暂停按钮调用setEnabled,然后再宣布取消暂停按钮。