ActionListenerTest2.java Source code

Java tutorial

Introduction

Here is the source code for ActionListenerTest2.java

Source

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class ActionListenerTest2 {

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Select File");
        button.addActionListener(new MyActionListener());
        frame.add(button);

        frame.pack();
        frame.setVisible(true);
    }
}

class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        int returnVal = fileChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.print(fileChooser.getSelectedFile().getName());
        }
    }
}