java - 通过另一个 JButton 启用/禁用一个 JButton

标签 java swing jbutton

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

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

关于java - 通过另一个 JButton 启用/禁用一个 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368674/

相关文章:

java - 使用 camera2 api 连续绘制相机框架?

java - 尝试使用 eclipse 将文件推送到 android 设备时出现问题

java - 矩形绘图java Swing GUI的问题

java - 如何在 Java Swing 中导出图像而不显示它

java - 如何让 Jbutton 填充 JPanel 以便按钮之间没有空格?

JAVA:jButton setBackground 在单击事件上发生变化

java - Spring 不提供 html 文件

java - 安卓开发: Combining two Java files

java - Java 中颜色值的问题

java - 如何改变JButton的大小?