Swing JFileChooser Class



Swing JFileChooser Class

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

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

public class JFileChooserDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JFileChooserDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("File Chooser", JLabel.CENTER);
    msgLabel = new JLabel("File Name :", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JFileChooserDemo demo = new JFileChooserDemo();
    demo.selectFile();
  }

  private void selectFile() {

    JButton btnFileOpen = new JButton("Select File");
    final JFileChooser fileDialog = new JFileChooser();

    btnFileOpen.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {

       int ret = fileDialog.showOpenDialog(mainFrame);

       if (ret == JFileChooser.APPROVE_OPTION) {
            File file = fileDialog.getSelectedFile();
            msgLabel.setText(file.getName());
        } else {
            msgLabel.setText("No file Selection.");
        }
      }
    });

    mainPanel.add(btnFileOpen);
    mainFrame.setVisible(true);
  }
}

Output :

Swing JFileChooser Class