Example usage for javax.swing JFileChooser setAccessory

List of usage examples for javax.swing JFileChooser setAccessory

Introduction

In this page you can find the example usage for javax.swing JFileChooser setAccessory.

Prototype

@BeanProperty(preferred = true, description = "Sets the accessory component on the JFileChooser.")
public void setAccessory(JComponent newAccessory) 

Source Link

Document

Sets the accessory component.

Usage

From source file:Main.java

public static void main(String[] argv) {
    JFileChooser chooser = new JFileChooser();
    chooser.setAccessory(new MyAccessory(chooser));
    chooser.showOpenDialog(null);//  w w w .  ja v a  2 s. c  o m
}

From source file:MainClass.java

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");
    }//from   w  ww.  ja va 2s. co  m
}

From source file:FileSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JFileChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    final JLabel directoryLabel = new JLabel();
    contentPane.add(directoryLabel, BorderLayout.NORTH);

    final JLabel filenameLabel = new JLabel();
    contentPane.add(filenameLabel, BorderLayout.SOUTH);

    final JButton button = new JButton("Open FileChooser");
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            Component parent = (Component) actionEvent.getSource();
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.setAccessory(new LabelAccessory(fileChooser));
            FileView view = new JavaFileView();
            fileChooser.setFileView(view);
            int status = fileChooser.showOpenDialog(parent);
            if (status == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                directoryLabel.setText(selectedFile.getParent());
                filenameLabel.setText(selectedFile.getName());
            } else if (status == JFileChooser.CANCEL_OPTION) {
                directoryLabel.setText(" ");
                filenameLabel.setText(" ");
            }//from w ww . ja  v  a 2s.c om
        }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);

    frame.setSize(300, 200);
    frame.setVisible(true);
}

From source file:FilterSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JFileChooser Filter Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    final JLabel directoryLabel = new JLabel();
    contentPane.add(directoryLabel, BorderLayout.NORTH);

    final JLabel filenameLabel = new JLabel();
    contentPane.add(filenameLabel, BorderLayout.SOUTH);

    final JButton button = new JButton("Open FileChooser");
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            Component parent = (Component) actionEvent.getSource();
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.setAccessory(new LabelAccessory(fileChooser));
            FileFilter filter1 = new ExtensionFileFilter(null, new String[] { "JPG", "JPEG" });
            //        fileChooser.setFileFilter(filter1);
            fileChooser.addChoosableFileFilter(filter1);
            FileFilter filter2 = new ExtensionFileFilter("gif", new String[] { "gif" });
            fileChooser.addChoosableFileFilter(filter2);
            fileChooser.setFileView(new JavaFileView());
            int status = fileChooser.showOpenDialog(parent);
            if (status == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                directoryLabel.setText(selectedFile.getParent());
                filenameLabel.setText(selectedFile.getName());
            } else if (status == JFileChooser.CANCEL_OPTION) {
                directoryLabel.setText(" ");
                filenameLabel.setText(" ");
            }//from w w  w.  j  a va 2s  .c  om
        }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);

    frame.setSize(300, 200);
    frame.setVisible(true);
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java

public static JFileChooser getFileChooser(Component parent, JFileChooser fileChooser, JComponent accessory) {
    fileChooser = initFileChooser(fileChooser, null);
    fileChooser.setAccessory(accessory);
    return fileChooser;
}

From source file:ch.fork.AdHocRailway.ui.locomotives.configuration.LocomotiveConfig.java

public void chooseLocoImage() {
    File previousLocoDir = ctx.getPreviousLocoDir();
    if (previousLocoDir == null) {
        previousLocoDir = new File("locoimages");
    }//from w w  w. j a  va 2s.  c om
    final JFileChooser chooser = new JFileChooser(previousLocoDir);

    final ImagePreviewPanel preview = new ImagePreviewPanel();
    chooser.setAccessory(preview);
    chooser.addPropertyChangeListener(preview);

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "Image Files";
        }

        @Override
        public boolean accept(final File f) {
            if (f.isDirectory()) {
                return true;
            }
            if (StringUtils.endsWithAny(f.getName().toLowerCase(), ".png", ".gif", ".bmp", ".jpg")) {
                return true;
            }
            return false;
        }
    });

    final int ret = chooser.showOpenDialog(LocomotiveConfig.this);
    if (ret == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        ctx.setPreviousLocoDir(selectedFile.getParentFile());
        presentationModel.getBean().setImage(selectedFile.getName());
        final String image = presentationModel.getBean().getImage();
        presentationModel.getBean()
                .setImageBase64(LocomotiveImageHelper.getImageBase64(presentationModel.getBean()));
        if (image != null && !image.isEmpty()) {
            imageLabel.setIcon(LocomotiveImageHelper.getLocomotiveIcon(presentationModel.getBean()));
            pack();
        } else {
            imageLabel.setIcon(null);
            pack();
        }
    }
}

From source file:de.juwimm.cms.content.panel.PanDocuments.java

private void upload(String prosa, Integer unit, Integer viewComponentId, Integer documentId) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    JFileChooser fc = new JFileChooser();
    int ff = fc.getChoosableFileFilters().length;
    FileFilter[] fft = fc.getChoosableFileFilters();
    for (int i = 0; i < ff; i++) {
        fc.removeChoosableFileFilter(fft[i]);
    }/*w  w w  .  j  a  v  a 2s . co m*/
    fc.addChoosableFileFilter(new DocumentFilter());
    fc.setAccessory(new ImagePreview(fc));
    fc.setDialogTitle(prosa);
    fc.setMultiSelectionEnabled(true);
    fc.setCurrentDirectory(Constants.LAST_LOCAL_UPLOAD_DIR);
    int returnVal = fc.showDialog(this, Messages.getString("panel.content.documents.addDocument"));

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File[] files = fc.getSelectedFiles();
        uploadFiles(files, unit, viewComponentId, documentId);
        Constants.LAST_LOCAL_UPLOAD_DIR = fc.getCurrentDirectory();
    }
    this.setCursor(Cursor.getDefaultCursor());
}

From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java

private void loadBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBackupButtonActionPerformed
    File databaseStore = new File(Main.getWorkingDirectory(), "comps");
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm"));

    JPanel optionsPanel = new JPanel();

    optionsPanel.setBorder(/*from w w  w  .j  a  v a  2  s. com*/
            new CompoundBorder(new EmptyBorder(0, 10, 0, 10), new TitledBorder("Load backup options")));
    JCheckBox preserveIDCheckbox = new JCheckBox("Preserve competition ID");
    optionsPanel.add(preserveIDCheckbox);

    chooser.setAccessory(optionsPanel);

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        /* input zip file */
        File file = chooser.getSelectedFile();
        /* construct output directory */
        File dir = new File(databaseStore, file.getName());
        int suffix = 0;
        while (dir.exists()) {
            suffix++;
            dir = new File(databaseStore, file.getName() + "_" + suffix);
        }
        /* unzip */
        try {
            ZipUtils.unzipFile(dir, file);

            /* change id */
            Properties props = new Properties();
            FileReader fr = new FileReader(new File(dir, "info.dat"));
            props.load(fr);
            fr.close();
            if (!preserveIDCheckbox.isSelected()) {
                props.setProperty("UUID", UUID.randomUUID().toString());
            }
            props.setProperty("name", props.getProperty("name") + " - " + dateFormat.format(new Date()));
            FileWriter fw = new FileWriter(new File(dir, "info.dat"));
            props.store(fw, "");
            fw.close();

            /* update gui */
            checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            GUIUtils.displayError(null, "Error while opening file: " + e.getMessage());
        }
    }
}

From source file:com.mgmtp.perfload.loadprofiles.ui.AppFrame.java

/**
 * Exports the events file for perfLoad tests. This method is registered on the {@link EventBus}
 * and called when the specified event is posted.
 * /*from  ww w.  jav a  2  s .co m*/
 * @param e
 *            the event that triggers calling of this method when posted on the event bus
 */
@Subscribe
public void exportEventListForPerfLoad(final ToolsExportEventListAction.Event e) throws IOException {
    if (checkLoadProfileEntityDirty() && checkLoadProfilePropertiesDirty()) {
        File dir = loadProfileEventsFile != null ? loadProfileEventsFile
                : loadProfileConfigFile.getParentFile();
        JFileChooser fc = SwingUtils.createFileChooser(dir,
                "Load Profile BaseLoadProfileEvent Files (*.perfload)", "perfload");
        fc.setAccessory(new SaveAccessoryPanel());

        if (loadProfileEventsFile == null) {
            loadProfileEventsFile = new File(
                    FilenameUtils.removeExtension(loadProfileConfigFile.getAbsolutePath()) + ".perfload");
        }

        File file = showSaveDialog(fc, loadProfileEventsFile, "perfload");
        if (file != null) {
            loadProfileEventsFile = file;

            LoadProfileConfig lpc = createLoadProfileConfig();
            LoadTestConfiguration ltc = loadProfilesController.createLoadTestConfiguration(lpc,
                    getSelectedTargets(), getSelectedClients());

            List<LoadCurveAssignment> loadCurveAssignments = ltc.getLoadCurveAssignments();
            Set<Operation> operations = newHashSet();
            int caCount = loadCurveAssignments.size();

            double maxTime = 0; // max time for histogram creation

            List<LoadCurve> loadCurves = newArrayListWithCapacity(caCount);
            for (LoadCurveAssignment loadCurveAssignment : loadCurveAssignments) {
                LoadCurve loadCurve = loadCurveAssignment.getLoadCurve();
                loadCurves.add(loadCurve);
                operations.add(loadCurveAssignment.getOperation());
                double[] timeValues = loadCurve.getTimeValues();
                maxTime = max(maxTime, timeValues[timeValues.length - 1]);
            }

            EventDistributor.addScaledLoadCurvesToAssignments(ltc, loadCurves);

            List<LoadEvent> clientEventList = EventDistributor.createClientEventList(ltc);
            List<BaseLoadProfileEvent> events = newArrayListWithExpectedSize(clientEventList.size());

            // One time and marker events are added separately

            for (OneTime oneTime : getOneTimes()) {
                double startTimeInHours = oneTime.t0 / 60d;

                // We must add one event per target
                for (Target target : oneTime.targets) {
                    LoadEvent event = new LoadEvent(startTimeInHours, oneTime.getOperation());
                    event.setProcessId(0); // 1 added later to make it zero-based
                    event.setDaemonId(1);
                    event.setTarget(target);
                    clientEventList.add(event);
                }
            }

            events.addAll(clientEventList);

            for (Marker marker : getMarkers()) {
                double time = marker.left / 60d;
                MarkerEvent event = new MarkerEvent(marker.name, time, MarkerEvent.Type.left);
                events.add(event);

                time = marker.right / 60d;
                event = new MarkerEvent(marker.name, time, MarkerEvent.Type.right);
                events.add(event);
            }

            Collections.sort(events, new LoadEventComparator());

            StrBuilder sb = new StrBuilder();
            sb.appendln("# Created: " + new Date());
            sb.appendln("# Load Profile Config File: " + loadProfileConfigFile.getName());
            sb.append("# Load Profile Name: " + txtName.getText());

            EventDistributor.writeEventListForPerfLoadClientsToFile(file, sb.toString(), events);

            // Create additional histogram file if selected
            dir = file.getParentFile();
            final String baseName = FilenameUtils.getBaseName(file.getName());
            int numClients = ltc.getClients().size();
            SaveAccessoryPanel sap = (SaveAccessoryPanel) fc.getAccessory();
            Collection<LoadEvent> loadEvents = transform(filter(clientEventList, new IsLoadEventPredicate()),
                    new EventToLoadEventFunction());

            if (sap.isEventDistriChecked()) {
                for (int i = 0; i < numClients; ++i) {
                    for (LoadCurve loadCurve : loadCurves) {
                        File f = new File(dir,
                                baseName + "-event-distri-client-" + i + "-" + loadCurve.getName() + ".csv");
                        PlotFileCreator.createPlot(f, loadEvents, loadCurve, i,
                                LoadCurveCalculator.timeUnit_minute);
                    }
                }
            }

            if (sap.isOperationHistogramChecked()) {
                for (Operation operation : operations) {
                    String opName = operation.getName();
                    File f = new File(dir, baseName + "-histogram-operation-" + opName + ".csv");
                    PlotFileCreator.createOperationHistogram(f, loadEvents, opName, (int) maxTime * 2, 0.,
                            maxTime, LoadCurveCalculator.timeUnit_minute);
                }
            }

            if (sap.isClientLoadHistrogramChecked()) {
                for (int i = 0; i < numClients; i++) {
                    File f = new File(dir, baseName + "-histogram-client-load-" + i + ".csv");
                    PlotFileCreator.createClientHistogram(f, loadEvents, i, (int) maxTime * 2, 0., maxTime,
                            LoadCurveCalculator.timeUnit_minute);
                }
            }
        }
    }
}

From source file:org.photovault.swingui.BrowserWindow.java

/** 
Shows an file selection dialog that allows user to select a
file to import. After that shows the PhotoInfo dialog to allow the
user to edit the eriginal information about the file. 
*//* w  ww. ja  v  a2 s .co  m*/

protected void importFile() {
    // Show the file chooser dialog
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setAccessory(new ImagePreview(fc));
    fc.setMultiSelectionEnabled(true);

    int retval = fc.showDialog(window, "Import");
    if (retval == JFileChooser.APPROVE_OPTION) {
        // Add the selected file to the database and allow user to edit its attributes
        final File[] files = fc.getSelectedFiles();

        final ProgressDlg pdlg = new ProgressDlg(window, true);

        // Add all the selected files to DB
        final PhotoInfo[] photos = new PhotoInfo[files.length];
        Thread importThread = new Thread() {
            @Override
            public void run() {

                for (int n = 0; n < files.length; n++) {
                    try {
                        photos[n] = PhotoInfo.addToDB(files[n]);
                        pdlg.setProgressPercent((n * 100) / files.length);
                        pdlg.setStatus("" + (n + 1) + " of " + files.length + " files imported.");
                    } catch (Exception e) {
                        log.error("Unexpected exception: " + e.getMessage());
                    }
                }
                pdlg.completed();
            }
        };

        importThread.start();
        pdlg.setVisible(true);

        // Show editor dialog for the added photos
        // PhotoInfoDlg dlg = new PhotoInfoDlg( window, false, photos );
        PhotoInfoDlg dlg = null;
        dlg.showDialog();
    }
}