UPDATE:
A nicer way to add an ActionListener to an anonymous object can be done by using the double brace initialization syntax noted here. Here is an example of that:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GuiTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 300);
JPanel base = new JPanel();
base.setLayout(new BorderLayout());
JPanel north = new JPanel();
Component comp1 = north.add(new JLabel("Name"));
System.out.println("comp1 class type: " + comp1.getClass().getName());
Component comp2 = north.add(new JTextField());
System.out.println("comp2 class type: " + comp2.getClass().getName());
Component comp3 = north.add(new JButton("Enter"));
System.out.println("comp3 class type: " + comp3.getClass().getName());
north.add(new JButton("Exit") {{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("EXIT");
}
});
}});
base.add(north);
frame.getContentPane().add(base);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
After searching through the Java API, I found that the add
method returns the component being added. Unfortunately, it is just a generic Component
object and can't be chained without a cast. But you can get the added object like this:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GuiTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 300);
JPanel base = new JPanel();
base.setLayout(new BorderLayout());
JPanel north = new JPanel();
Component comp1 = north.add(new JLabel("Name"));
System.out.println("comp1 class type: " + comp1.getClass().getName());
Component comp2 = north.add(new JTextField());
System.out.println("comp2 class type: " + comp2.getClass().getName());
Component comp3 = north.add(new JButton("Enter"));
System.out.println("comp3 class type: " + comp3.getClass().getName());
((JButton)north.add(new JButton("Exit")))
.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("EXIT");
}
});
base.add(north);
frame.getContentPane().add(base);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This code is complete and verifiable (I tested it on my Arch Linux x64 machine). It is a little ugly, but works.