[英]Java actionlistener actionPerformed in different class
I have two classes: the main one and one called "Window". 我有两个类:主要的一个和称为“窗口”的一个。 There are some buttons in the Window class, is it possible to let the "main" class know what happened?
Window类中有一些按钮,是否可以让“ main”类知道发生了什么? In short, buttons in class "Window" should trigger some stuff in the main class.
简而言之,“窗口”类中的按钮应触发主类中的某些内容。
Or should I just type everything in the "Window" class? 还是应该在“窗口”类中键入所有内容?
Yes it is possible. 对的,这是可能的。
ActionListener
is interface,so you can let "main" class implement this interface and pass it to Window class as parameter in Windows class constructor. ActionListener
是接口,因此您可以让“主要”类实现此接口,并将其作为Windows类构造函数中的参数传递给Window类。
Following code snippet that can help you: 以下代码段可以为您提供帮助:
Main class: 主班:
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
//button clicked, so do you job here
}
}
Windows class: Windows类:
package test;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Window extends JPanel
{
public Window(ActionListener listener)
{
JButton b = new JButton("Button 1");
b.addActionListener(listener);
add(b);
//do other stuff
}
public static void main(String[] args)
{
Window w = new Window(new Main());
//continue with initialization process
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.