Saturday, December 21, 2013

Example of using ActionListener

Example to implement ActionListener for Swing UI elements.

Example of using ActionListener
Example of using ActionListener

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame 
    implements ActionListener{

    JTextArea textArea;
    JButton button1, button2;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myFrame.prepareUI();

        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane panel = new JScrollPane(textArea);
        panel.setPreferredSize(new Dimension(300, 100));
        
        button1 = new JButton("My Button 1");
        button1.addActionListener(this);
        button2 = new JButton("My Button 2");
        button2.addActionListener(anotherActionListener);
        
        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(button1, BorderLayout.PAGE_START);
        getContentPane().add(button2, BorderLayout.PAGE_END);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        textArea.setText(e.getActionCommand());
    }
    
    ActionListener anotherActionListener = new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.setText("anotherActionListener: " 
                    + e.getActionCommand());
        }
        
    };
}


Related: Example of using KeyListener

No comments:

Post a Comment