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?
解决方案
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 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
}
}