Java actionlistener action在不同的类中执行 [英] Java actionlistener actionPerformed in different class

查看:157
本文介绍了Java actionlistener action在不同的类中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:主要类和一个名为Window的类。
Window类中有一些按钮,是否可以让主类知道发生了什么?简而言之,Window类中的按钮应该触发主类中的一些东西。

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? In short, buttons in class "Window" should trigger some stuff in the main class.

或者我应该只在Window类中键入所有内容?

Or should I just type everything in the "Window" class?

推荐答案

是的,这是可能的。 ActionListener 是接口,因此您可以让main类实现此接口并将其作为Windows类构造函数中的参数传递给Window类。

关注可以帮助您的代码段:

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.
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类:

Windows class:

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
    }
}

这篇关于Java actionlistener action在不同的类中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆