Java JFileChooser .setAccessory (JComponent newAccessory)
Syntax
JFileChooser.setAccessory(JComponent newAccessory) has the following syntax.
public void setAccessory(JComponent newAccessory)
Example
In the following code shows how to use JFileChooser.setAccessory(JComponent newAccessory) method.
/*from w ww . j a va 2 s. c o m*/
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 Main {
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());
}
}
}
}
Home »
Java Tutorial »
javax.swing »
Java Tutorial »
javax.swing »