![](/img/trans.png)
[英]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.