Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:edu.harvard.mcz.imagecapture.jobs.JobRepeatOCR.java

private List<File> getFileList() {
    String pathToCheck = "";
    if (scan != SCAN_ALL) {
        // Find the path in which to include files.
        File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
        File startPoint = null;// w ww . ja  v  a2s .  c  o m
        // If it isn't null, retrieve the image base directory from properties, and test for read access.
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                    "Can't start scan.  Don't know where images are stored.  Set imagbase property.",
                    "Can't Scan.", JOptionPane.ERROR_MESSAGE);
        } else {
            imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
            if (imagebase != null) {
                if (imagebase.canRead()) {
                    startPoint = imagebase;
                } else {
                    // If it can't be read, null out imagebase
                    imagebase = null;
                }
            }
            if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
                // A scan start point has been provided, don't launch a dialog.
                startPoint = startPointSpecific;
            }
            if (imagebase == null || scan == SCAN_SELECT) {
                // launch a file chooser dialog to select the directory to scan
                final JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                    fileChooser.setCurrentDirectory(startPointSpecific);
                } else {
                    if (Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                        fileChooser
                                .setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                                        .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                    }
                }
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    log.debug("Selected base directory: " + file.getName() + ".");
                    startPoint = file;
                } else {
                    //TODO: handle error condition
                    log.error("Directory selection cancelled by user.");
                }
                //TODO: Filechooser to pick path, then save (if SCAN_ALL) imagebase property. 
                //Perhaps.  Might be undesirable behavior.
                //Probably better to warn that imagebase is null;
            }

            // Check that startPoint is or is within imagebase.
            if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
                String base = Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                log.error("Tried to scan directory (" + startPoint.getPath()
                        + ") outside of base image directory (" + base + ")");
                String message = "Can't scan and database files outside of base image directory (" + base + ")";
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                        "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
            } else {

                // run in separate thread and allow cancellation and status reporting

                // walk through directory tree

                if (!startPoint.canRead()) {
                    JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                            "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                            "Can't Scan.", JOptionPane.YES_NO_OPTION);
                } else {
                    pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);
                }
            }
        }
    }

    // Retrieve a list of all specimens in state OCR
    SpecimenLifeCycle sls = new SpecimenLifeCycle();
    Specimen pattern = new Specimen();
    pattern.setWorkFlowStatus(WorkFlowStatus.STAGE_0);
    List<Specimen> specimens = sls.findByExample(pattern);
    ArrayList<File> files = new ArrayList<File>();
    for (int i = 0; i < specimens.size(); i++) {
        Specimen s = specimens.get(i);
        Set<ICImage> images = s.getICImages();
        Iterator<ICImage> iter = images.iterator();
        while (iter.hasNext() && runStatus != RunStatus.STATUS_TERMINATED) {
            ICImage image = (ICImage) iter.next();
            if (scan == SCAN_ALL || image.getPath().startsWith(pathToCheck)) {
                // Add image for specimen to list to check
                File imageFile = new File(
                        ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));
                files.add(imageFile);
                counter.incrementFilesSeen();
            }
        }
    }
    String message = "Found " + files.size() + " Specimen records on which to repeat OCR.";
    log.debug(message);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage(message);

    return files;
}

From source file:cs.cirg.cida.CIDAView.java

@Action
public void loadExperiment() {
    JFileChooser chooser = new JFileChooser(experimentController.getDataDirectory());
    FileNameExtensionFilter filter = new FileNameExtensionFilter(CIDAConstants.DIALOG_TXT_CSV_MSG, "txt",
            "csv");
    chooser.setFileFilter(filter);/*from w w  w. j a v a 2 s  .c o  m*/
    chooser.setMultiSelectionEnabled(true);
    int returnVal = chooser.showOpenDialog(this.getComponent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            File[] files = chooser.getSelectedFiles();
            String[] experimentNames = null;
            experimentNames = new String[files.length];
            for (int i = 0; i < files.length; ++i) {
                File dataFile = files[i];
                String tmpName = dataFile.getName().substring(0, dataFile.getName().lastIndexOf("."));
                if (editResultsNameCheckBox.isSelected()) {
                    CIDAInputDialog dialog = new CIDAInputDialog(this.getFrame(),
                            CIDAConstants.RENAME_EXPERIMENT_MSG, tmpName);
                    dialog.displayPrompt();
                    tmpName = dialog.getInput();
                }
                experimentNames[i] = tmpName;
            }
            experimentController.addExperiments(files, experimentNames);
            this.selectExperiment();
        } catch (CIlibIOException ex) {
            CIDAPromptDialog dialog = exceptionController.handleException(this.getFrame(), ex,
                    CIDAConstants.EXCEPTION_OCCURRED);
            dialog.displayPrompt();
        }
    }
}

From source file:org.biojava.bio.view.MotifAnalyzer.java

private JPanel getStatisticsTab(int excelNum) throws IOException {
    JPanel panel = new JPanel();
    GroupLayout panelLayout = new GroupLayout((JComponent) panel);
    panel.setLayout(panelLayout);//from w w  w .j a v a  2 s . c o  m
    panel.setPreferredSize(new java.awt.Dimension(676, 557));

    Object[][] tableData = FileConverterTools.readExcel(FileNames.getStatisticsExcelFileName(excelNum));
    Object columnName[] = new Object[tableData[0].length];
    for (int i = 0; i < columnName.length; i++)
        columnName[i] = i;
    tableData = null; //free memory

    final JTable table = new JTable();
    JScrollPane jScrollPane = new JScrollPane(table);
    table.setFont(new Font(Font.DIALOG, Font.BOLD, 15));
    table.setEnabled(false);
    File file = new File(FileNames.getStatisticsExcelFileName(excelNum));
    JTableReadTableModelTask task = new JTableReadTableModelTask(file, null, null, table);
    task.execute();

    JButton button = new JButton("Save to Excel");
    panelLayout.setVerticalGroup(panelLayout.createSequentialGroup()
            .addComponent(jScrollPane, GroupLayout.PREFERRED_SIZE, 485, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(button,
                    GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
            .addContainerGap(40, 40));
    panelLayout.setHorizontalGroup(panelLayout.createParallelGroup()
            .addComponent(jScrollPane, GroupLayout.Alignment.LEADING, 0, 676, Short.MAX_VALUE)
            .addGroup(GroupLayout.Alignment.LEADING,
                    panelLayout.createSequentialGroup().addGap(0, 493, Short.MAX_VALUE)
                            .addComponent(button, GroupLayout.PREFERRED_SIZE, 143, GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(40, 40)));
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showOpenDialog(MotifAnalyzer.this.mainFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    //File file = new File(fc.getSelectedFile().getCanonicalPath());
                    //JTableWriteTableModelTask task = new JTableWriteTableModelTask(file, null, null, table);
                    //task.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    return panel;
}

From source file:ElectionGUI.java

private void saveElectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveElectionBtnActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setApproveButtonText("Save");
    fileChooser.setCurrentDirectory(folder);
    int result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        folder = fileChooser.getCurrentDirectory();
        File selectedFile = fileChooser.getSelectedFile();
        Store2dElection store = new Store2dElection(this, selectedFile);
        store.writeToFile();/*from  w ww. j  a v a  2  s. co m*/
        systemTxt.append("-Election saved successfully." + eol);
        saved = true;
    } else if (result == JFileChooser.CANCEL_OPTION) {
        systemTxt.append("-Saving cancelled" + eol);
    }
}

From source file:ffx.ui.KeywordPanel.java

/**
 * Give the user a File Dialog Box so they can select a key file.
 *///from   w ww  .j a  v a2 s .  c om
public void keyOpen() {
    if (fileOpen && KeywordComponent.isKeywordModified()) {
        int option = JOptionPane.showConfirmDialog(this, "Save Changes First", "Opening New File",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
        if (option == JOptionPane.CANCEL_OPTION) {
            return;
        } else if (option == JOptionPane.YES_OPTION) {
            keySave(currentKeyFile);
        }
        keyClear();
    }
    JFileChooser d = MainPanel.resetFileChooser();
    if (currentSystem != null) {
        File cwd = currentSystem.getFile();
        if (cwd != null && cwd.getParentFile() != null) {
            d.setCurrentDirectory(cwd.getParentFile());
        }
    }
    d.setAcceptAllFileFilterUsed(false);
    d.setFileFilter(MainPanel.keyFileFilter);
    d.setDialogTitle("Open KEY File");
    int result = d.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File newKeyFile = d.getSelectedFile();
        if (newKeyFile != null && newKeyFile.exists() && newKeyFile.canRead()) {
            keyOpen(newKeyFile);
        }
    }
}

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

/**
 * Opens a load profile configuration. This method is registered on the {@link EventBus} and
 * called when the specified event is posted.
 * //from   w ww  . j  ava  2 s .  c  o m
 * @param e
 *            the event that triggers calling of this method when posted on the event bus
 */
@Subscribe
public void openLoadProfileConfiguration(final FileOpenLoadProfileConfigAction.Event e) {
    if (checkLoadProfileEntityDirty() && checkLoadProfilePropertiesDirty()) {
        File dir = loadProfileConfigFile != null ? loadProfileConfigFile : new File(".");
        JFileChooser fc = SwingUtils.createFileChooser(dir, "XML Files (*.xml)", "xml");
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                removeTableListeners();

                activeLoadProfileConfig = loadProfilesController.loadProfileConfig(file);

                txtName.setText(activeLoadProfileConfig.getName());
                taDescription.setText(activeLoadProfileConfig.getDescription());
                for (SelectionDecorator sd : decoratedTargets) {
                    sd.setSelected(activeLoadProfileConfig.getTargets().contains(sd.getBaseObject()));
                }
                for (SelectionDecorator sd : decoratedClients) {
                    sd.setSelected(activeLoadProfileConfig.getClients().contains(sd.getBaseObject()));
                }
                loadProfilesController.getTreeItems().clear();
                for (LoadProfileEntity lpe : activeLoadProfileConfig.getLoadProfileEntities()) {
                    loadProfilesController.addOrUpdateLoadProfileEntity(lpe);
                }
                ModelUtils.updateTargetDecorators(decoratedTargets, oneTimeDecoratedTargets,
                        loadProfilesController.getTargets(), true);
                expandTree();
                updateGraph();
                tblClients.repaint();
                tblTargets.repaint();
                loadProfileConfigFile = file;
                if (loadProfileEventsFile != null && !getBaseName(loadProfileConfigFile.getName())
                        .equals(getBaseName(loadProfileEventsFile.getName()))) {
                    loadProfileEventsFile = null;
                }

                setTitle(APP_TITLE + " - [" + loadProfileConfigFile + "]");
                dirty = false;
            } catch (JAXBException ex) {
                throw new RuntimeException("Error loading load profile configuration: " + file, ex);
            } finally {
                addTableListeners();
            }
        }
    }
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private File chooseFileForOpen(final String title, final File initial,
        final AtomicReference<FileFilter> selectedFilter, final FileFilter... filter) {
    final JFileChooser chooser = new JFileChooser(initial);
    for (final FileFilter f : filter) {
        chooser.addChoosableFileFilter(f);
    }/* w  w  w .j ava 2s . c  o  m*/
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setMultiSelectionEnabled(false);
    chooser.setDialogTitle(title);
    chooser.setFileFilter(filter[0]);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    final File result;
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        result = chooser.getSelectedFile();
        if (selectedFilter != null) {
            selectedFilter.set(chooser.getFileFilter());
        }
    } else {
        result = null;
    }
    return result;
}

From source file:com.raddle.tools.MergeMain.java

private void initGUI() {
    try {//www. jav  a  2 s  . co m
        {
            this.setBounds(0, 0, 1050, 600);
            getContentPane().setLayout(null);
            this.setTitle("\u5c5e\u6027\u6587\u4ef6\u6bd4\u8f83");
            {
                sourceTxt = new JTextField();
                getContentPane().add(sourceTxt);
                sourceTxt.setBounds(12, 12, 373, 22);
            }
            {
                sourceBtn = new JButton();
                getContentPane().add(sourceBtn);
                sourceBtn.setText("\u6253\u5f00");
                sourceBtn.setBounds(406, 12, 74, 22);
                sourceBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        JFileChooser fileChooser = new JFileChooser(); // 
                        fileChooser.addChoosableFileFilter(
                                new FileNameExtensionFilter("", "properties"));
                        File curFile = new File(sourceTxt.getText());
                        if (curFile.exists()) {
                            fileChooser.setCurrentDirectory(curFile.getParentFile());
                        }
                        int result = fileChooser.showOpenDialog(MergeMain.this);
                        if (result == JFileChooser.APPROVE_OPTION) {
                            File selected = fileChooser.getSelectedFile();
                            source = new PropertyHolder(selected, "utf-8");
                            sourceTxt.setText(selected.getAbsolutePath());
                            properties.setProperty("left.file", selected.getAbsolutePath());
                            savePropMergeFile();
                            compare();
                        }
                    }
                });
            }
            {
                targetTxt = new JTextField();
                getContentPane().add(targetTxt);
                targetTxt.setBounds(496, 12, 419, 22);
            }
            {
                targetBtn = new JButton();
                getContentPane().add(targetBtn);
                targetBtn.setText("\u6253\u5f00");
                targetBtn.setBounds(935, 12, 81, 22);
                targetBtn.setSize(74, 22);
                targetBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        JFileChooser fileChooser = new JFileChooser(); // 
                        fileChooser.addChoosableFileFilter(
                                new FileNameExtensionFilter("", "properties"));
                        File curFile = new File(targetTxt.getText());
                        if (curFile.exists()) {
                            fileChooser.setCurrentDirectory(curFile.getParentFile());
                        }
                        int result = fileChooser.showOpenDialog(MergeMain.this);
                        if (result == JFileChooser.APPROVE_OPTION) {
                            File selected = fileChooser.getSelectedFile();
                            target = new PropertyHolder(selected, "utf-8");
                            targetTxt.setText(selected.getAbsolutePath());
                            properties.setProperty("right.file", selected.getAbsolutePath());
                            savePropMergeFile();
                            compare();
                        }
                    }
                });
            }
            {
                jScrollPane1 = new JScrollPane();
                getContentPane().add(jScrollPane1);
                jScrollPane1.setBounds(12, 127, 373, 413);
                {
                    ListModel sourceListModel = new DefaultComboBoxModel(new String[] {});
                    sourceList = new JList();
                    jScrollPane1.setViewportView(sourceList);
                    sourceList.setAutoscrolls(true);
                    sourceList.setModel(sourceListModel);
                    sourceList.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent evt) {
                            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                                PropertyLine v = (PropertyLine) sourceList.getSelectedValue();
                                if (v != null) {
                                    int ret = JOptionPane.showConfirmDialog(MergeMain.this,
                                            "?" + v.getKey() + "?");
                                    if (ret == JOptionPane.YES_OPTION) {
                                        v.setState(LineState.deleted);
                                        compare();
                                        sourceList.setSelectedValue(v, true);
                                    }
                                }
                            }
                        }
                    });
                    sourceList.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent evt) {
                            if (evt.getClickCount() == 2) {
                                Object v = sourceList.getSelectedValue();
                                updatePropertyLine((PropertyLine) v);
                                sourceList.setSelectedValue(v, true);
                            }
                        }
                    });
                    sourceList.addListSelectionListener(new ListSelectionListener() {

                        @Override
                        public void valueChanged(ListSelectionEvent evt) {
                            if (sourceList.getSelectedValue() != null) {
                                PropertyLine pl = (PropertyLine) sourceList.getSelectedValue();
                                if (target != null) {
                                    PropertyLine p = target.getLine(pl.getKey());
                                    if (p != null) {
                                        TextDiffResult rt = TextdiffUtil.getDifferResult(p.toString(),
                                                pl.toString());
                                        diffResultPane.setText("" + rt.getTargetHtml() + "<br/>?"
                                                + rt.getSrcHtml());
                                        selectLine(targetList, p);
                                        return;
                                    }
                                }
                                TextDiffResult rt = TextdiffUtil.getDifferResult("", pl.toString());
                                diffResultPane.setText(
                                        "" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml());

                            }
                        }
                    });
                }
            }
            {
                jScrollPane2 = new JScrollPane();
                getContentPane().add(jScrollPane2);
                jScrollPane2.setBounds(496, 127, 419, 413);
                {
                    ListModel targetListModel = new DefaultComboBoxModel(new String[] {});
                    targetList = new JList();
                    jScrollPane2.setViewportView(targetList);
                    targetList.setAutoscrolls(true);
                    targetList.setModel(targetListModel);
                    targetList.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent evt) {
                            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                                PropertyLine v = (PropertyLine) targetList.getSelectedValue();
                                if (v != null) {
                                    int ret = JOptionPane.showConfirmDialog(MergeMain.this,
                                            "?" + v.getKey() + "?");
                                    if (ret == JOptionPane.YES_OPTION) {
                                        v.setState(LineState.deleted);
                                        compare();
                                        targetList.setSelectedValue(v, true);
                                    }
                                }
                            }
                        }
                    });
                    targetList.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent evt) {
                            if (evt.getClickCount() == 2) {
                                Object v = targetList.getSelectedValue();
                                updatePropertyLine((PropertyLine) v);
                                targetList.setSelectedValue(v, true);
                            }
                        }
                    });
                    targetList.addListSelectionListener(new ListSelectionListener() {

                        @Override
                        public void valueChanged(ListSelectionEvent evt) {
                            if (targetList.getSelectedValue() != null) {
                                PropertyLine pl = (PropertyLine) targetList.getSelectedValue();
                                if (source != null) {
                                    PropertyLine s = source.getLine(pl.getKey());
                                    if (s != null) {
                                        TextDiffResult rt = TextdiffUtil.getDifferResult(pl.toString(),
                                                s.toString());
                                        diffResultPane.setText("" + rt.getTargetHtml() + "<br/>?"
                                                + rt.getSrcHtml());
                                        selectLine(sourceList, s);
                                        return;
                                    }
                                }
                                TextDiffResult rt = TextdiffUtil.getDifferResult(pl.toString(), "");
                                diffResultPane.setText(
                                        "" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml());
                            }
                        }
                    });
                }
            }
            {
                sourceSaveBtn = new JButton();
                getContentPane().add(sourceSaveBtn);
                sourceSaveBtn.setText("\u4fdd\u5b58");
                sourceSaveBtn.setBounds(406, 45, 74, 22);
                sourceSaveBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        int result = JOptionPane.showConfirmDialog(MergeMain.this,
                                "???\n"
                                        + source.getPropertyFile().getAbsolutePath());
                        if (result == JOptionPane.YES_OPTION) {
                            source.saveFile();
                            JOptionPane.showMessageDialog(MergeMain.this, "??");
                            clearState(source);
                            compare();
                        }
                    }
                });
            }
            {
                targetSaveBtn = new JButton();
                getContentPane().add(targetSaveBtn);
                targetSaveBtn.setText("\u4fdd\u5b58");
                targetSaveBtn.setBounds(935, 45, 81, 22);
                targetSaveBtn.setSize(74, 22);
                targetSaveBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        int result = JOptionPane.showConfirmDialog(MergeMain.this,
                                "????\n"
                                        + target.getPropertyFile().getAbsolutePath());
                        if (result == JOptionPane.YES_OPTION) {
                            target.saveFile();
                            JOptionPane.showMessageDialog(MergeMain.this, "??");
                            clearState(target);
                            compare();
                        }
                    }
                });
            }
            {
                toTargetBtn = new JButton();
                getContentPane().add(toTargetBtn);
                toTargetBtn.setText("->");
                toTargetBtn.setBounds(406, 221, 74, 22);
                toTargetBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        Object[] oo = sourceList.getSelectedValues();
                        for (Object selected : oo) {
                            PropertyLine s = (PropertyLine) selected;
                            if (s != null && target != null) {
                                PropertyLine t = target.getLine(s.getKey());
                                if (t == null) {
                                    PropertyLine n = s.clone();
                                    n.setState(LineState.added);
                                    target.addPropertyLineAtSuitedPosition(n);
                                } else if (!t.getValue().equals(s.getValue())) {
                                    t.setState(LineState.updated);
                                    t.setValue(s.getValue());
                                } else if (t.getState() == LineState.deleted) {
                                    if (t.getValue().equals(t.getOriginalValue())) {
                                        t.setState(LineState.original);
                                    } else {
                                        t.setState(LineState.updated);
                                    }
                                }
                                compare();
                            }
                        }
                    }
                });
            }
            {
                toSourceBtn = new JButton();
                getContentPane().add(toSourceBtn);
                toSourceBtn.setText("<-");
                toSourceBtn.setBounds(406, 255, 74, 22);
                toSourceBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        Object[] oo = targetList.getSelectedValues();
                        for (Object selected : oo) {
                            PropertyLine t = (PropertyLine) selected;
                            if (t != null && source != null) {
                                PropertyLine s = source.getLine(t.getKey());
                                if (s == null) {
                                    PropertyLine n = t.clone();
                                    n.setState(LineState.added);
                                    source.addPropertyLineAtSuitedPosition(n);
                                } else if (!s.getValue().equals(t.getValue())) {
                                    s.setState(LineState.updated);
                                    s.setValue(t.getValue());
                                } else if (s.getState() == LineState.deleted) {
                                    if (s.getValue().equals(s.getOriginalValue())) {
                                        s.setState(LineState.original);
                                    } else {
                                        s.setState(LineState.updated);
                                    }
                                }
                                compare();
                            }
                        }
                    }
                });
            }
            {
                jScrollPane3 = new JScrollPane();
                getContentPane().add(jScrollPane3);
                jScrollPane3.setBounds(12, 73, 903, 42);
                {
                    diffResultPane = new JTextPane();
                    jScrollPane3.setViewportView(diffResultPane);
                    diffResultPane.setBounds(12, 439, 903, 63);
                    diffResultPane.setContentType("text/html");
                    diffResultPane.setPreferredSize(new java.awt.Dimension(901, 42));
                }
            }
            {
                compareBtn = new JButton();
                getContentPane().add(compareBtn);
                compareBtn.setText("\u6bd4\u8f83");
                compareBtn.setBounds(406, 139, 74, 22);
                compareBtn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        compare();
                    }
                });
            }
            {
                sourceReloadBtn = new JButton();
                getContentPane().add(sourceReloadBtn);
                sourceReloadBtn.setText("\u91cd\u65b0\u8f7d\u5165");
                sourceReloadBtn.setBounds(12, 40, 64, 29);
                sourceReloadBtn.setSize(90, 22);
                sourceReloadBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        if (sourceTxt.getText().length() > 0) {
                            File curFile = new File(sourceTxt.getText().trim());
                            if (curFile.exists()) {
                                source = new PropertyHolder(curFile, "utf-8");
                                sourceTxt.setText(curFile.getAbsolutePath());
                                properties.setProperty("left.file", curFile.getAbsolutePath());
                                savePropMergeFile();
                                compare();
                            } else {
                                JOptionPane.showMessageDialog(MergeMain.this,
                                        "" + curFile.getAbsolutePath() + "?");
                            }
                        }
                    }
                });
            }
            {
                targetReloadBtn = new JButton();
                getContentPane().add(targetReloadBtn);
                targetReloadBtn.setText("\u91cd\u65b0\u8f7d\u5165");
                targetReloadBtn.setBounds(839, 45, 90, 22);
                targetReloadBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        if (targetTxt.getText().length() > 0) {
                            File curFile = new File(targetTxt.getText().trim());
                            if (curFile.exists()) {
                                target = new PropertyHolder(curFile, "utf-8");
                                targetTxt.setText(curFile.getAbsolutePath());
                                properties.setProperty("right.file", curFile.getAbsolutePath());
                                savePropMergeFile();
                                compare();
                            } else {
                                JOptionPane.showMessageDialog(MergeMain.this,
                                        "" + curFile.getAbsolutePath() + "?");
                            }
                        }
                    }
                });
            }
            {
                helpBtn = new JButton();
                getContentPane().add(helpBtn);
                helpBtn.setText("\u5e2e\u52a9");
                helpBtn.setBounds(405, 338, 38, 29);
                helpBtn.setSize(74, 22);
                helpBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("?").append("\n");
                        sb.append("del").append("\n");
                        sb.append("??").append("\n");
                        sb.append(": /.prop-merge/prop-merge.properties").append("\n");
                        JOptionPane.showMessageDialog(MergeMain.this, sb.toString());
                    }
                });
            }
            {
                sourceEditBtn = new JButton();
                getContentPane().add(sourceEditBtn);
                sourceEditBtn.setText("\u7f16\u8f91\u6587\u4ef6");
                sourceEditBtn.setBounds(108, 40, 90, 22);
                sourceEditBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        if (sourceTxt.getText().length() > 0) {
                            File curFile = new File(sourceTxt.getText());
                            editFile(curFile);
                        }
                    }
                });
            }
            {
                targetEditBtn = new JButton();
                getContentPane().add(targetEditBtn);
                targetEditBtn.setText("\u7f16\u8f91\u6587\u4ef6");
                targetEditBtn.setBounds(743, 45, 90, 22);
                targetEditBtn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        if (targetTxt.getText().length() > 0) {
                            File curFile = new File(targetTxt.getText());
                            editFile(curFile);
                        }
                    }
                });
            }
        }
        pack();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ElectionGUI.java

private void loadElectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadElectionBtnActionPerformed
    if (!generalPreferencesCheckBox.isSelected()) {
        //Confirmation of discarding an election2D that is not saved
        boolean discard = true;
        if (election2D != null && !saved) {
            int response = JOptionPane.showConfirmDialog(null,
                    "Current " + "election is not saved, are you sure you want to load " + "an election?" + eol
                            + "Press \"No\" to save current " + "election in a file.",
                    "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (response == JOptionPane.NO_OPTION) {
                discard = false;//  w w w.  j av a  2  s.co  m
            }
        }

        if (discard) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(folder);
            int result = fileChooser.showOpenDialog(this);

            if (result == JFileChooser.APPROVE_OPTION) {
                folder = fileChooser.getCurrentDirectory();
                File selectedFile = fileChooser.getSelectedFile();
                Parse2dElection parser = new Parse2dElection();
                parser.parseFromFile(selectedFile);
                if (parser.getErr() == null) {
                    election2D = parser.getElection();
                    nTxtField.setText(String.valueOf(election2D.getNumberOfVoters()));
                    mTxtField.setText(String.valueOf(election2D.getNumberOfCandidates()));
                    kTxtField.setText(String.valueOf(election2D.getCommitteeSize()));
                    xLimit = parser.getxLimit();
                    xLimitTxtField.setText(String.valueOf(xLimit));
                    yLimit = parser.getyLimit();
                    yLimitTxtField.setText(String.valueOf(yLimit));
                    nClusters = parser.getnClusters();
                    nClusterTxtField.setText(String.valueOf(nClusters));
                    mClusters = parser.getmClusters();
                    mClusterTxtField.setText(String.valueOf(mClusters));

                    systemTxt.append("-Election loaded." + eol);
                    plotResultsBtn.setEnabled(true);
                    saveElectionBtn.setEnabled(true);
                    consistencyBtn.setEnabled(false);
                    saved = true;
                } else {
                    systemTxt.append(parser.getErr() + eol);
                }
            } else if (result == JFileChooser.CANCEL_OPTION) {
                systemTxt.append("-Loading cancelled." + eol);
            }
        }
    } else {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(folder);
        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            folder = fileChooser.getCurrentDirectory();
            File selectedFile = fileChooser.getSelectedFile();
            ParseGeneralElection parser = new ParseGeneralElection();
            parser.parseFromFile(selectedFile);

            if (parser.getErr() == null) {
                ArrayList<Voter> voters = parser.getVoters();
                ArrayList<Candidate> candidates = parser.getCandidates();
                n = voters.size();
                m = candidates.size();
                try {
                    int x = Integer.parseInt(kTxtField.getText());
                    if (x < 1 || x > 100 || x > m) {
                        throw (new Exception());
                    }
                    k = x;
                } catch (Exception e) {
                    kTxtField.setBackground(Color.cyan);
                    kTxtField.setText("1");
                    k = 1;
                    systemTxt.append("-Committee size was invalid. It has " + "been set equal to 1." + eol);
                }

                electionGP = new Election(k, voters, candidates, false);
                plotResultsBtn.setEnabled(true);
                consistencyBtn.setEnabled(false);
                systemTxt
                        .append("-Election " + selectedFile.getName() + " has been loaded successfully." + eol);
            } else {
                systemTxt.append(parser.getErr() + eol);
            }
        } else if (result == JFileChooser.CANCEL_OPTION) {
            systemTxt.append("-Loading cancelled." + eol);
        }
    }
}

From source file:PreferencesTest.java

public PreferencesFrame() {
    // get position, size, title from preferences

    Preferences root = Preferences.userRoot();
    final Preferences node = root.node("/com/horstmann/corejava");
    int left = node.getInt("left", 0);
    int top = node.getInt("top", 0);
    int width = node.getInt("width", DEFAULT_WIDTH);
    int height = node.getInt("height", DEFAULT_HEIGHT);
    setBounds(left, top, width, height);

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);/*from  w w  w  .  j a  v a  2s  . com*/

    // set up file chooser that shows XML files

    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    // accept all files ending with .xml
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
        }

        public String getDescription() {
            return "XML files";
        }
    });

    // set up menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem exportItem = new JMenuItem("Export preferences");
    menu.add(exportItem);
    exportItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                    node.exportSubtree(out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem importItem = new JMenuItem("Import preferences");
    menu.add(importItem);
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    InputStream in = new FileInputStream(chooser.getSelectedFile());
                    Preferences.importPreferences(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            node.putInt("left", getX());
            node.putInt("top", getY());
            node.putInt("width", getWidth());
            node.putInt("height", getHeight());
            node.put("title", getTitle());
            System.exit(0);
        }
    });
}