java - 如何在缅因州 JFrame 中禁用按钮后从其他 JFrame 启用按钮?

标签 java swing jframe actionlistener

我有两个类(class):

public class Screen1 extends javax.swing.JFrame {
...
//disables JButton1 after it is clicked on
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){                                         
      setVisible(false);  
....
}
}

还有另一个类:

public class Screen2 extends javax.swing.JFrame {
...
//Clicking on JButton2 is supposed to enable JButton1 (from Screen1) again     
...
}

现在,再次启用 JButton1 最简单的方法是什么?我无法从 Screen1 直接访问 JButton1 来设置再次可见。我研究了 ActionListeners 和 Modal JDialogs,从我的 Google 搜索来看,它们似乎是解决这个问题的一些有希望的方法(可能?)。 但我真的找不到一个我能理解的例子(我更像是一个 Java 初学者)。

任何有用的意见都会受到赞赏!

最佳答案

请在下面找到这个简单的示例

Screen2 包含一个默认禁用的 JButton,Screen1 包含另一个可以启用第一个按钮的 JButton

屏幕2

public class Screen2 extends JPanel {

    private JButton button;

    public Screen2() {
        button = new JButton("Button");
        button.setEnabled(false); //the button is disabled by default
        this.add(button);// add the button to the screen
    }

    // this method will be used to enable the button
    public void changeButtonStatus(boolean flag) {
        button.setEnabled(flag);
    }
}

屏幕1

public class Screen1 {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Screen1");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        JButton button = new JButton("Enable the button");
        Screen2 screen2 = new Screen2();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                screen2.changeButtonStatus(true); //Call the method that enable the button
            }
        });
        frame.add(screen2, BorderLayout.SOUTH);
        frame.add(button, BorderLayout.NORTH);
        frame.setVisible(true);
    }
}

输出

首先,Screen2 JButton 被禁用

enter image description here

当点击 Screen1 JButton 时,Screen2 JButton 将启用。

enter image description here

关于java - 如何在缅因州 JFrame 中禁用按钮后从其他 JFrame 启用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980516/

相关文章:

java - BorderLayout.CENTER 内的 JScrollPane 不调整大小

java - JLabel 背景图片...奇怪的行为?

java - 如何知道java框架的坐标?

java - Swing:将功能键 (F2) 设置为加速器

java - 将 HTML 从 JEditorPane 复制到外部应用程序时出现问题

java - 如何获取在另一个字符串中找到的字符串的真实结束索引

java - 此位置不允许使用注释 @Index

java - graphics.setColor(颜色);不工作

java - 如何验证 Person 类中的输入

java - 在 Java 中执行符号数学