2

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.

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

4

1 回答 1

3

对的,这是可能的。ActionListener是接口,所以你可以让“main”类实现这个接口,并在Windows类构造函数中将它作为参数传递给Window类。
以下代码片段可以帮助您:

主类:

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

    }
}

窗户类:

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
    }
}
于 2013-10-16T16:09:18.500 回答