[英]How to use ActionListener when the button function is in another class
[英]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);
}
其次,為您的JFrame
或JPanel
類實現此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.