I have a problem with ActionListener. If I use an anonymous class everything works good, if the MainFrame class implements ActionListener everything works good. But if I create an extern class and implement ActionListener I get NullPointerException.
How can I fix this problem using an extern class that implement ActionListener interface?
Thanks in advance!
This is the code:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class App {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new MainFrame("Hello world Swing");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
MainFrame code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
JTextArea textArea;
public MainFrame(String title) {
super(title);
Container c = getContentPane();
c.setLayout(new BorderLayout());
textArea = new JTextArea();
JButton button = new JButton("Click me!");
c.add(textArea, BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);
button.addActionListener(new ListenApp());
}
}
ListenApp code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class ListenApp implements ActionListener {
MainFrame frame;
@Override
public void actionPerformed(ActionEvent e) {
frame.textArea.append("Hello\n");
}
}