簡體   English   中英

如何在涉及 ActionListener 的另一個類中啟用按鈕

[英]How to enable a button in another class involving ActionListener

我在 Java Eclipse 中引用了這段代碼:

public class ClassWithButton extends JFrame{
    private final JPanel Your_Panel_name;

    public void enableButtons() {
    for (Component c : Your_Panel_name.getComponents()) {
      if (c instanceof JButton) 
         c.setEnabled(true);
     }
  }
}

然后是一個實現ActionListener.java的類

public class ActionListenerImpl implements ActionListener{
    public void actionPerformed(ActionEvent e){

    }
}

我在一個擴展 JFrame 的類中有一個按鈕,我有一個面板,我在其中禁用了兩個按鈕。 我有另一個擴展 ActionListener 的類,當我按下面板上的另一個按鈕時,我希望啟用 2 個禁用的按鈕,我該怎么做?

我建議您定義自己的Listener類來實現您的目標。

首先,定義一個Listener類。

public interface ButtonEnabledListener {
    void buttonEnabled(boolean isEnabled);
}

其次,為您的JFrameJPanel類實現此Listener

public YourJPanel extends JPanel implements ButtonEnabledListener {
    void buttonEnabled(boolean isEnabled) {
        for (JButton button : buttons) {
            button.setEnabled(isEnabled);
        }
    }
}

最后,在另一個類中,傳入您的框架或面板並觸發事件。 由於您的類實現了 ActionListener,因此在實現的方法中觸發事件。

public AnotherClass implements ActionListener {
    JButton yourButton;
    ButtonEnabledListener listener;
    public AnotherClass(ButtonEnabledListener yourPanel) {
       yourButton = new JButton("enable buttons in my panel");
       yourButton.addActionListener(this);
       listener = yourPanel;
    }
    public void actionPerformed(ActionEvent e) {
        listener.buttonEnabled(true);                    
    }
}

使用您提供的代碼,這是參考如何工作的一個快速示例,但這不是我實現它的方式。

public class ClassWithButton extends JFrame{
    private final JPanel Your_Panel_name;
    ActionListenerImpl act;
    JButton otherButton;
    public ClassWithButton()
    {
        act = new ActionListenerImpl(this);
        otherButton = new JButton("Click to enable");
        otherButton.addActionListener(act);
    }
    public void enableButtons() {
        for (Component c : Your_Panel_name.getComponents()) {
            if (c instanceof JButton) 
                c.setEnabled(true);
        }
    }
}

public class ActionListenerImpl implements ActionListener{
    ClassWithButton b;
    public ActionListenerImpl(ClassWithButton b)
    {
        this.b = b;
    }
    public void actionPerformed(ActionEvent e){
        b.enableButtons();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM