// Project: Swing // Module: listener // Source code file MyFrame.java // A listener is added to the three buttons, // which can report which button was clicked. The event handler // then goes back to the button and obtain the // caption from the clicked button. import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame { // Declare and instantiate controls. private JButton buttonA = new JButton("Button A"); private JButton buttonB = new JButton("Button B"); private JButton buttonC = new JButton("Button C"); private JTextArea textArea = new JTextArea( ); private JPanel contentPanel = new JPanel( ); // The main method creates the frame. public static void main(String[] args) { new MyFrame( ); } public MyFrame( ) { // Set text in title bar. super("SwingControls Example"); // Don't use layout manager contentPanel.setLayout(null); // Add button to panel buttonA.setLocation(25, 25); buttonA.setSize(150, 25); contentPanel.add(buttonA); // Add button to panel buttonB.setLocation(25, 75); buttonB.setSize(150, 25); contentPanel.add(buttonB); // Add button to panel buttonC.setLocation(25, 125); buttonC.setSize(150, 25); contentPanel.add(buttonC); // Add textarea to panel textArea.setLocation(25, 175); textArea.setSize(300, 50); contentPanel.add(textArea); // Add actionlisteners to buttons. Listener listener = new Listener( ); buttonA.addActionListener(listener); buttonB.addActionListener(listener); buttonC.addActionListener(listener); // Set the panel to be used to display // controls on the frame. this.setContentPane(contentPanel); // Set width of frame to 400 pixels and // height to 500 pixels. this.setSize(400, 300); // Make frame visible. this.setVisible(true); } // Private inner class for the listener that // listens for button clicks. private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton btn = (JButton) e.getSource( ); textArea.setText(btn.getText( ) + " was pressed."); } } }