import javax.swing.*; import java.awt.event.*; class ButtonListener implements ActionListener { // each button listener stores the name of the button private String text; // given the text when it's created public ButtonListener(String t) { text = t; } @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "You pushed button " + text); } } public class LayoutExample { public static void addButton(String text, JFrame f) { // add a button object JButton button = new JButton(text); button.addActionListener(new ButtonListener(text)); f.getContentPane().add(button); } public static void main(String[] args) { // create and set up the window. JFrame frame = new JFrame("Button Example!"); // make the program close when the window closes frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create the box layout frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); // add some buttons addButton("A", frame); addButton("B", frame); addButton("C", frame); addButton("D", frame); // display the window. frame.pack(); frame.setVisible(true); } }