MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JLabel;

public class MainClass {

    public static void main(String[] a) {
        JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setAccessory(new LabelAccessory(fileChooser));
        int status = fileChooser.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println(selectedFile.getParent());
            System.out.println(selectedFile.getName());
        } else if (status == JFileChooser.CANCEL_OPTION) {
            System.out.println("JFileChooser.CANCEL_OPTION");
        }
    }
}

class LabelAccessory extends JLabel implements PropertyChangeListener {

    public LabelAccessory(JFileChooser chooser) {
        chooser.addPropertyChangeListener(this);
        setPreferredSize(new Dimension(100, 100));
    }

    public void propertyChange(PropertyChangeEvent changeEvent) {
        String changeName = changeEvent.getPropertyName();
        if (changeName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
            File file = (File) changeEvent.getNewValue();
            if (file != null) {
                setText(file.getName());
            }
        }
    }
}