繁体   English   中英

JButton ActionListener没有响应

[英]JButton ActionListener not responding

我在网上其他任何地方都找不到答案,所以我来到了这里。 如果我的代码中的错误非常明显,我会提前道歉; 我对java swing还是很陌生。 这是怎么回事:我创建了一个名为toggleElevators的JButton,我希望它在单击时可以更改文本。 我已经创建了一个ActionListener并将其添加到toggleElevators 我现在想要的只是让JButton在单击Click meClicked时更改文本。

首先,这是执行JFrame时的外观图:

的JFrame

注意:有一个第三类,但这纯粹是为了在左侧绘制图片。 它与GridLayout或JButton无关。

Run类(创建框架并添加toggleElevators

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.JFrame;

public class Run extends Input{

Input i = new Input();

public static void main(String[] args) {
    new Run();
}

public Run() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new JFrame("Elevators");
            frame.setLayout(new GridLayout(0, 3));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Elevators(Color.MAGENTA, true));
            frame.add(new Elevators(Color.ORANGE, false));
            frame.setSize(800,600);
            frame.setResizable(false);

            frame.getContentPane().add(toggleElevators); //adds toggleElevators button to JFrame
            i.addButtonListeners(); //calls method defined in Input class, which adds the ActionListener to the toggleElevators button

            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

}

Input类(创建toggleElevators JButton及其ActionListener):

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Input {
JButton toggleElevators = new JButton("Click me.");

public void addButtonListeners() {
    toggleElevators.addActionListener(new toggleElevatorsListener());
}

class toggleElevatorsListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        toggleElevators.setText("Clicked.");
        System.out.println("ActionListener called."); //I know the ActionListener is not being called because this line is not being printed out in the console
    }
}
}

您的Run类扩展Input,但还具有一个名为i的Input。 您将this.toggleElevators添加到框架中,但您将监听器添加到i.toggleElevators

从您的班级中删除i字段。 我也会完全忘记定义和扩展Input类。 它没有任何作用,似乎比帮助您更令人困惑。

您可以在Run类中创建一个新的Input ,而Run类还可以扩展Input

调用i.addButtonListeners(); 操作侦听器将添加到itoggleElevators ,而不是您从Input类继承的toggleElevators

尝试addButtonListeners()

您的Run类扩展了Input 因此,它有自己的toggleElevators ,它是在框架中设置的那个。 但是, i有自己的toggleElevators ,用于设置事件侦听器。 因此,它们不是设置在框架中的一个上,而是设置在永不使用的框架上。

您可以简单地删除i对象。 Run扩展Input ,它可以直接调用该方法,然后将侦听器添加到其自己的toggleElevators

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM