Java 通过另一个JButton启用/禁用JButton

Java 通过另一个JButton启用/禁用JButton,java,swing,jbutton,Java,Swing,Jbutton,我有“暂停”和“取消暂停”的按钮。当用户暂停程序时,应禁用暂停按钮,并启用取消暂停按钮。我不知道怎么写。取消暂停按钮有效,但暂停按钮无效,因为“取消暂停无法解决”。如何处理?这是我的密码: final JButton pause = new JButton("Pause"); pause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {

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

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

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

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

从发布的代码判断,它是未解决的,因为它只是该方法的局部(我假设您有一个
init
方法,或者上面发布的代码在您的构造函数中)。尝试全局声明您的按钮;这会解决你的问题。@slanecek不客气。如果它解决了你的问题,考虑接受答案。或者,我假设在他的班级里有多个<代码> JButton < /代码> s。您还应该建议他的类应该实现
ActionListener
,只需检查
JButton
它是什么,而不是为每个
JButton
创建一个新的
ActionListener
。是的,我会在7分钟内接受。我也会考虑使用ActualListInter。“谢谢你们两位。”JoshM No Josh,我个人认为这是一个糟糕的做法。如果您想直接在类中实现
ActionListener
,那么创建一个单独的、称为“controller”的类,该类实现
ActionListener
,并将您的逻辑放在那里。只是个人意见。@brano88这是一种怎样的坏习惯?