调用 .addActionListener() 时使用哪些参数?
What parameters are used when .addActionListener() is called?
我最近在 Java 中学到了很多东西,但有些事情一直困扰着我。我学习/被教导如何在程序涉及构造函数时使用 ActionListeners,例如,
public class test extends JFrame implements ActionListener {
JButton button;
public test
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
test testprogram = new test();
test.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent clickevent) {
if (clickevent.GetSource() == button) {
//DoSomething
}
}
它是 class 的实例,它将处理 ActionEvent
。
Register an instance of the event handler class as a listener on one
or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
它可以是实现 ActionListener
.
的任何东西
您可能要考虑不让您的 JFrame
实现 ActionListener
:这意味着
- 它是 class 接口的一部分,它实现了
actionPerformed
;但您可能不希望其他 classes 直接调用它。
- 您只能实施它 "once",因此您最终必须有条件逻辑来确定事件的来源,然后适当地处理它。
另一种方法是创建一个 button
特定的动作侦听器:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent clickevent) {
// Don't need to check if it is from button, nothing else
// could have created the event.
}
});
并从 test
class 中删除 implements ActionListener
。
我最近在 Java 中学到了很多东西,但有些事情一直困扰着我。我学习/被教导如何在程序涉及构造函数时使用 ActionListeners,例如,
public class test extends JFrame implements ActionListener {
JButton button;
public test
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
test testprogram = new test();
test.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent clickevent) {
if (clickevent.GetSource() == button) {
//DoSomething
}
}
它是 class 的实例,它将处理 ActionEvent
。
Register an instance of the event handler class as a listener on one or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
它可以是实现 ActionListener
.
您可能要考虑不让您的 JFrame
实现 ActionListener
:这意味着
- 它是 class 接口的一部分,它实现了
actionPerformed
;但您可能不希望其他 classes 直接调用它。 - 您只能实施它 "once",因此您最终必须有条件逻辑来确定事件的来源,然后适当地处理它。
另一种方法是创建一个 button
特定的动作侦听器:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent clickevent) {
// Don't need to check if it is from button, nothing else
// could have created the event.
}
});
并从 test
class 中删除 implements ActionListener
。