Example usage for javax.swing JFileChooser JFileChooser

List of usage examples for javax.swing JFileChooser JFileChooser

Introduction

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

Prototype

public JFileChooser() 

Source Link

Document

Constructs a JFileChooser pointing to the user's default directory.

Usage

From source file:com.alvermont.terraj.stargen.ui.StargenFrame.java

/** Creates new form StargenFrame */
public StargenFrame() {
    initComponents();//w w  w.j a  v  a 2 s.co m

    LookAndFeelUtils.getInstance().setSystemLookAndFeel(true, this);

    xmlChooser = new JFileChooser();
    xmlChooser.addChoosableFileFilter(new XMLFileFilter());

    updateFromParameters(this.parameters);
    validate();
}

From source file:es.emergya.ui.gis.popups.SaveGPXDialog.java

private SaveGPXDialog(final List<Layer> capas) {
    super("Consulta de Posiciones GPS");
    setResizable(false);/* w w  w  .  jav  a  2s  . c om*/
    setAlwaysOnTop(true);
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    JPanel dialogo = new JPanel(new BorderLayout());
    dialogo.setBackground(Color.WHITE);
    dialogo.setBorder(new EmptyBorder(10, 10, 10, 10));

    JPanel central = new JPanel(new FlowLayout());
    central.setOpaque(false);
    final JTextField nombre = new JTextField(15);
    nombre.setEditable(false);
    central.add(nombre);
    final JButton button = new JButton("Examinar...", LogicConstants.getIcon("button_nuevo"));
    central.add(button);
    final JButton aceptar = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showSaveDialog(SaveGPXDialog.this) == JFileChooser.APPROVE_OPTION) {
                nombre.setText(fileChooser.getSelectedFile().getAbsolutePath());
                aceptar.setEnabled(true);
            }
        }
    });

    dialogo.add(central, BorderLayout.CENTER);

    JPanel botones = new JPanel(new FlowLayout());
    botones.setOpaque(false);

    aceptar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String base_url = nombre.getText() + "_";
            for (Layer layer : capas) {
                if (layer instanceof GpxLayer) {
                    GpxLayer gpxLayer = (GpxLayer) layer;
                    File f = new File(base_url + gpxLayer.name + ".gpx");

                    boolean sobreescribir = !f.exists();

                    try {
                        while (!sobreescribir) {
                            String original = f.getCanonicalPath();
                            f = checkFileOverwritten(nombre, f);
                            sobreescribir = !f.exists() || original.equals(f.getCanonicalPath());
                        }
                    } catch (NullPointerException t) {
                        log.debug("Cancelando creacion de fichero: " + t);
                        sobreescribir = false;
                    } catch (Throwable t) {
                        log.error("Error comprobando la sobreescritura", t);
                        sobreescribir = false;
                    }

                    if (sobreescribir) {
                        try {
                            f.createNewFile();
                        } catch (IOException e1) {
                            log.error(e1, e1);
                        }
                        if (!(f.isFile() && f.canWrite()))
                            JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                    "No tengo permiso para escribir en " + f.getAbsolutePath());
                        else {
                            try {
                                OutputStream out = new FileOutputStream(f);
                                GpxWriter writer = new GpxWriter(out);
                                writer.write(gpxLayer.data);
                                out.close();
                            } catch (Throwable t) {
                                log.error("Error al escribir el gpx", t);
                                JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                        "Ocurri un error al escribir en " + f.getAbsolutePath());
                            }
                        }
                    } else
                        log.error("Por errores anteriores no se escribio el fichero");
                } else
                    log.error("Una de las capas no era gpx: " + layer.name);
            }
            SaveGPXDialog.this.dispose();

        }

        private File checkFileOverwritten(final JTextField nombre, File f) throws Exception {
            String nueva = JOptionPane.showInputDialog(nombre, i18n.getString("savegpxdialog.overwrite"),
                    "Sobreescribir archivo", JOptionPane.QUESTION_MESSAGE, null, null, f.getCanonicalPath())
                    .toString();
            log.debug("Nueva ruta: " + nueva);
            return new File(nueva);
        }
    });

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            SaveGPXDialog.this.dispose();
        }
    });

    aceptar.setEnabled(false);
    botones.add(aceptar);
    botones.add(cancelar);
    dialogo.add(botones, BorderLayout.SOUTH);

    add(dialogo);
    setPreferredSize(new Dimension(300, 200));
    pack();

    int x;
    int y;

    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }

    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }

        @Override
        public void windowClosing(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }
    });
}

From source file:sample.fa.ScriptRunnerApplication.java

private void loadScript(ActionEvent ae) {
    JFileChooser jfc = new JFileChooser();
    jfc.showOpenDialog(scriptContents);/*w  w w .  j a  va  2s.  c  om*/
    if (jfc.getSelectedFile() != null) {
        loadScript(jfc.getSelectedFile());
    }
}

From source file:SciTK.Plot.java

/** 
* Save data for generic plot to file /*from   w  ww. j  a  v  a  2 s .  co  m*/
*/
public void saveData() {
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ExtensionFileFilter("CSV", new String[] { "csv,CSV" }));
    // remove default option:
    fc.setAcceptAllFileFilterUsed(false);

    // Select a file using the JFileChooser dialog:
    int fc_return = fc.showSaveDialog(this);

    if (fc_return == JFileChooser.APPROVE_OPTION) // user wants to save
    {
        //get the file name from the filter:
        File save_file = fc.getSelectedFile();

        // check to see if the user entered an extension:
        if (!save_file.getName().endsWith(".csv") && !save_file.getName().endsWith(".CSV")) {
            save_file = new File(save_file.getAbsolutePath() + ".csv");
        }

        // create a string to save
        String s = toString();

        // IO inside a try/catch
        try {
            // Create a File Writer
            FileWriter fw = new FileWriter(save_file);
            fw.write(s);
            fw.close();
        }
        // If there was an error, launch an error dialog box:
        catch (IOException e) {
            DialogError emsg = new DialogError(this, " There was an error saving the file."
                    + System.getProperty("line.separator") + e.getMessage());
        }
    }
}

From source file:net.pms.newgui.Wizard.java

public static void run(final PmsConfiguration configuration) {
    // Total number of questions
    int numberOfQuestions = Platform.isMac() ? 4 : 5;

    // The current question number
    int currentQuestionNumber = 1;

    String status = new StringBuilder().append(Messages.getString("Wizard.2")).append(" %d ")
            .append(Messages.getString("Wizard.4")).append(" ").append(numberOfQuestions).toString();

    Object[] okOptions = { Messages.getString("Dialog.OK") };

    Object[] yesNoOptions = { Messages.getString("Dialog.YES"), Messages.getString("Dialog.NO") };

    Object[] networkTypeOptions = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"),
            Messages.getString("Wizard.10") };

    if (!Platform.isMac()) {
        // Ask if they want UMS to start minimized
        int whetherToStartMinimized = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.3"),
                String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[1]);

        if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
            configuration.setMinimized(true);
        } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
            configuration.setMinimized(false);
        }//w  ww .j  a va 2  s  .  c om
    }

    // Ask if their network is wired, etc.
    int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, networkTypeOptions, networkTypeOptions[1]);

    switch (networkType) {
    case JOptionPane.YES_OPTION:
        // Wired (Gigabit)
        configuration.setMaximumBitrate("0");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.NO_OPTION:
        // Wired (100 Megabit)
        configuration.setMaximumBitrate("90");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.CANCEL_OPTION:
        // Wireless
        configuration.setMaximumBitrate("30");
        configuration.setMPEG2MainSettings("Automatic (Wireless)");
        configuration.setx264ConstantRateFactor("Automatic (Wireless)");
        break;
    default:
        break;
    }

    // Ask if they want to hide advanced options
    int whetherToHideAdvancedOptions = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.11"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
        configuration.setHideAdvancedOptions(true);
    } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
        configuration.setHideAdvancedOptions(false);
    }

    // Ask if they want to scan shared folders
    int whetherToScanSharedFolders = JOptionPane.showOptionDialog(null,
            Messages.getString("Wizard.IsStartupScan"), String.format(status, currentQuestionNumber++),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToScanSharedFolders == JOptionPane.YES_OPTION) {
        configuration.setScanSharedFoldersOnStartup(true);
    } else if (whetherToScanSharedFolders == JOptionPane.NO_OPTION) {
        configuration.setScanSharedFoldersOnStartup(false);
    }

    // Ask to set at least one shared folder
    JOptionPane.showOptionDialog(null, Messages.getString("Wizard.12"),
            String.format(status, currentQuestionNumber++), JOptionPane.OK_OPTION,
            JOptionPane.INFORMATION_MESSAGE, null, okOptions, okOptions[0]);

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser;
                try {
                    chooser = new JFileChooser();
                } catch (Exception ee) {
                    chooser = new JFileChooser(new RestrictedFileSystemView());
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle(Messages.getString("Wizard.12"));
                chooser.setMultiSelectionEnabled(false);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    configuration.setOnlySharedDirectory(chooser.getSelectedFile().getAbsolutePath());
                } else {
                    // If the user cancels this option, the default directories will be used.
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException e) {
        LOGGER.error("Error when saving folders: ", e);
    }

    // The wizard finished, do not ask them again
    configuration.setRunWizard(false);

    // Save all changes
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        LOGGER.error("Error when saving changed configuration: ", e);
    }
}

From source file:com.titan.storagepanel.DownloadImageDialog.java

public DownloadImageDialog(final Frame frame) {
    super(frame, true);
    setTitle("Openstack vm os image");
    setBounds(100, 100, 947, 706);// w w  w. j a  v  a 2 s  .c  om
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));
    {
        JPanel panel = new JPanel();
        contentPanel.add(panel, BorderLayout.NORTH);
        panel.setLayout(new MigLayout("", "[41px][107.00px][27px][95.00px][24px][95.00px][]", "[27px]"));
        {
            JLabel lblSearch = new JLabel("Search");
            panel.add(lblSearch, "cell 0 0,alignx left,aligny center");
        }
        {
            searchTextField = new JSearchTextField();
            searchTextField.setPreferredSize(new Dimension(150, 40));
            panel.add(searchTextField, "cell 1 0,growx,aligny center");
        }
        {
            JLabel lblType = new JLabel("Type");
            panel.add(lblType, "cell 2 0,alignx left,aligny center");
        }
        {
            typeComboBox = new JComboBox(
                    new String[] { "All", "Ubuntu", "Fedora", "Redhat", "CentOS", "Gentoo", "Windows" });
            panel.add(typeComboBox, "cell 3 0,growx,aligny top");
        }
        {
            JLabel lblSize = new JLabel("Size");
            panel.add(lblSize, "cell 4 0,alignx left,aligny center");
        }
        {
            sizeComboBox = new JComboBox(new String[] { "0-700MB", ">700MB" });
            panel.add(sizeComboBox, "cell 5 0,growx,aligny top");
        }
        {
            JButton btnSearch = new JButton("Search");
            btnSearch.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    d.setVisible(true);
                }
            });
            panel.add(btnSearch, "cell 6 0");
        }
    }
    {
        JScrollPane scrollPane = new JScrollPane();
        contentPanel.add(scrollPane, BorderLayout.CENTER);
        {
            table = new JTable();
            table.setModel(tableModel);
            table.addMouseListener(new JTableButtonMouseListener(table));
            table.addMouseMotionListener(new JTableButtonMouseListener(table));
            scrollPane.setViewportView(table);
        }
    }
    {
        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);
        {
            JButton downloadButton = new JButton("Download");
            downloadButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (table.getSelectedRowCount() == 1) {
                        JFileChooser jf = new JFileChooser();
                        int x = jf.showSaveDialog(frame);
                        if (x == JFileChooser.APPROVE_OPTION) {
                            DownloadImage p = (DownloadImage) table.getValueAt(table.getSelectedRow(), 0);
                            DownloadFileDialog d = new DownloadFileDialog(frame, "Downloading image", true,
                                    p.file, jf.getSelectedFile());
                            CommonLib.centerDialog(d);
                            d.setVisible(true);
                        }
                    }
                }
            });
            panel.add(downloadButton);
        }
    }

    d = new JProgressBarDialog(frame, true);
    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.thread = new Thread() {
        public void run() {
            InputStream in = null;
            tableModel.columnNames.clear();
            tableModel.columnNames.add("image");
            tableModel.editables.clear();
            tableModel.editables.put(0, true);
            Vector<Object> col1 = new Vector<Object>();
            try {
                d.progressBar.setString("connecting to titan image site");
                in = new URL("http://titan-image.kingofcoders.com/titan-image.xml").openStream();
                String xml = IOUtils.toString(in);
                NodeList list = TitanCommonLib.getXPathNodeList(xml, "/images/image");
                for (int x = 0; x < list.getLength(); x++) {
                    DownloadImage downloadImage = new DownloadImage();
                    downloadImage.author = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/author/text()");
                    downloadImage.authorEmail = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/authorEmail/text()");
                    downloadImage.License = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/License/text()");
                    downloadImage.description = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/description/text()");
                    downloadImage.file = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/file/text()");
                    downloadImage.os = TitanCommonLib.getXPath(xml, "/images/image[" + (x + 1) + "]/os/text()");
                    downloadImage.osType = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/osType/text()");
                    downloadImage.uploadDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(
                            TitanCommonLib.getXPath(xml, "/images/image[" + (x + 1) + "]/uploadDate/text()"));
                    downloadImage.size = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/size/text()");
                    downloadImage.architecture = TitanCommonLib.getXPath(xml,
                            "/images/image[" + (x + 1) + "]/architecture/text()");
                    col1.add(downloadImage);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(frame, "Unable to connect titan image site !", "Error",
                        JOptionPane.ERROR_MESSAGE);
            } finally {
                IOUtils.closeQuietly(in);
            }
            tableModel.values.clear();
            tableModel.values.add(col1);
            tableModel.fireTableStructureChanged();
            table.getColumnModel().getColumn(0).setCellRenderer(new DownloadImageTableCellRenderer());
            //            table.getColumnModel().getColumn(0).setCellEditor(new DownloadImageTableCellEditor());
            for (int x = 0; x < table.getRowCount(); x++) {
                table.setRowHeight(x, 150);
            }
        }
    };
    d.setVisible(true);
}

From source file:App.java

/**
 * Initialize the contents of the frame.
 *//*from w w  w .j  av  a  2  s . co m*/
private void initialize() {

    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 750);
    frame.getContentPane().setLayout(null);

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "png");
    fc = new JFileChooser();
    fc.setFileFilter(filter);
    frame.getContentPane().add(fc);

    stepOne = new JLabel("");
    stepOne.setToolTipText("here comes something");
    stepOne.setIcon(new ImageIcon("img/stepOne.png"));
    stepOne.setBounds(266, -4, 67, 49);
    frame.getContentPane().add(stepOne);

    btnBrowse = new JButton("Browse");
    btnBrowse.setBounds(66, 6, 117, 29);
    frame.getContentPane().add(btnBrowse);

    btnTurnWebcamOn = new JButton("Take a picture with webcam");
    btnTurnWebcamOn.setBounds(66, 34, 212, 29);
    frame.getContentPane().add(btnTurnWebcamOn);

    JButton btnTakePictureWithWebcam = new JButton("Take a picture");
    btnTakePictureWithWebcam.setBounds(430, 324, 117, 29);
    frame.getContentPane().add(btnTakePictureWithWebcam);
    btnTakePictureWithWebcam.setVisible(false);

    JButton btnCancel = new JButton("Cancel");
    btnCancel.setBounds(542, 324, 117, 29);
    frame.getContentPane().add(btnCancel);
    btnCancel.setVisible(false);

    JButton btnSaveImage = new JButton("Save image");
    btnSaveImage.setBounds(497, 357, 117, 29);
    frame.getContentPane().add(btnSaveImage);
    btnSaveImage.setVisible(false);

    urlField = new JTextField();
    urlField.setBounds(66, 67, 220, 26);
    frame.getContentPane().add(urlField);
    urlField.setColumns(10);

    originalImageLabel = new JLabel();
    originalImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
    originalImageLabel.setBounds(33, 98, 300, 300);
    frame.getContentPane().add(originalImageLabel);

    stepTwo = new JLabel("");
    stepTwo.setToolTipText("here comes something else");
    stepTwo.setIcon(new ImageIcon("img/stepTwo.png"));
    stepTwo.setBounds(266, 413, 67, 49);
    frame.getContentPane().add(stepTwo);

    btnAnalyse = new JButton("Analyse image");
    btnAnalyse.setBounds(68, 423, 196, 29);
    frame.getContentPane().add(btnAnalyse);

    tagsField = new JTextArea();
    tagsField.setBounds(23, 479, 102, 89);
    tagsField.setLineWrap(true);
    tagsField.setWrapStyleWord(true);
    frame.getContentPane().add(tagsField);
    tagsField.setColumns(10);

    lblTags = new JLabel("Tags:");
    lblTags.setBounds(46, 451, 61, 16);
    frame.getContentPane().add(lblTags);

    descriptionField = new JTextArea();
    descriptionField.setLineWrap(true);
    descriptionField.setWrapStyleWord(true);
    descriptionField.setBounds(137, 479, 187, 89);
    frame.getContentPane().add(descriptionField);
    descriptionField.setColumns(10);

    lblDescription = new JLabel("Description:");
    lblDescription.setBounds(163, 451, 77, 16);
    frame.getContentPane().add(lblDescription);

    stepThree = new JLabel("");
    stepThree.setToolTipText("here comes something different");
    stepThree.setIcon(new ImageIcon("img/stepThree.png"));
    stepThree.setBounds(266, 685, 67, 49);
    frame.getContentPane().add(stepThree);

    JLabel lblImageType = new JLabel("Image type");
    lblImageType.setBounds(23, 580, 102, 16);
    frame.getContentPane().add(lblImageType);

    String[] imageTypes = { "unspecified", "AnimategGif", "Clipart", "Line", "Photo" };
    JComboBox imageTypeBox = new JComboBox(imageTypes);
    imageTypeBox.setBounds(137, 580, 187, 23);
    frame.getContentPane().add(imageTypeBox);

    JLabel lblSizeType = new JLabel("Size");
    lblSizeType.setBounds(23, 608, 102, 16);
    frame.getContentPane().add(lblSizeType);

    String[] sizeTypes = { "unspecified", "Small", "Medium", "Large", "Wallpaper" };
    JComboBox sizeBox = new JComboBox(sizeTypes);
    sizeBox.setBounds(137, 608, 187, 23);
    frame.getContentPane().add(sizeBox);

    JLabel lblLicenseType = new JLabel("License");
    lblLicenseType.setBounds(23, 636, 102, 16);
    frame.getContentPane().add(lblLicenseType);

    String[] licenseTypes = { "unspecified", "Public", "Share", "ShareCommercially", "Modify" };
    JComboBox licenseBox = new JComboBox(licenseTypes);
    licenseBox.setBounds(137, 636, 187, 23);
    frame.getContentPane().add(licenseBox);

    JLabel lblSafeSearchType = new JLabel("Safe search");
    lblSafeSearchType.setBounds(23, 664, 102, 16);
    frame.getContentPane().add(lblSafeSearchType);

    String[] safeSearchTypes = { "Strict", "Moderate", "Off" };
    JComboBox safeSearchBox = new JComboBox(safeSearchTypes);
    safeSearchBox.setBounds(137, 664, 187, 23);
    frame.getContentPane().add(safeSearchBox);

    btnSearchForSimilar = new JButton("Search for similar images");
    btnSearchForSimilar.setVisible(true);
    btnSearchForSimilar.setBounds(66, 695, 189, 29);
    frame.getContentPane().add(btnSearchForSimilar);

    // label to try urls to display images, not shown on the main frame
    labelTryLinks = new JLabel();
    labelTryLinks.setBounds(0, 0, 100, 100);

    foundImagesLabel1 = new JLabel();
    foundImagesLabel1.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel1.setBounds(400, 49, 250, 250);
    frame.getContentPane().add(foundImagesLabel1);

    foundImagesLabel2 = new JLabel();
    foundImagesLabel2.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel2.setBounds(400, 313, 250, 250);
    frame.getContentPane().add(foundImagesLabel2);

    foundImagesLabel3 = new JLabel();
    foundImagesLabel3.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel3.setBounds(673, 49, 250, 250);
    frame.getContentPane().add(foundImagesLabel3);

    foundImagesLabel4 = new JLabel();
    foundImagesLabel4.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel4.setBounds(673, 313, 250, 250);
    frame.getContentPane().add(foundImagesLabel4);

    progressBar = new JProgressBar();
    progressBar.setIndeterminate(true);
    progressBar.setStringPainted(true);
    progressBar.setBounds(440, 602, 440, 29);

    Border border = BorderFactory
            .createTitledBorder("We are checking every image, pixel by pixel, it may take a while...");
    progressBar.setBorder(border);
    frame.getContentPane().add(progressBar);
    progressBar.setVisible(false);

    btnHelp = new JButton("");
    btnHelp.setBorderPainted(false);
    ImageIcon btnIcon = new ImageIcon("img/helpRed.png");
    btnHelp.setIcon(btnIcon);
    btnHelp.setBounds(917, 4, 77, 59);
    frame.getContentPane().add(btnHelp);

    // all action listeners
    btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                openFilechooser();
            }
        }
    });

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

            setAllFoundImagesLabelsAndPreviewsToNull();
            btnTakePictureWithWebcam.setVisible(true);
            btnCancel.setVisible(true);
            turnCameraOn();
        }
    });

    btnTakePictureWithWebcam.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            btnSaveImage.setVisible(true);
            // take a photo with web camera
            imageWebcam = webcam.getImage();
            originalImage = imageWebcam;

            // to mirror the image we create a temporary file, flip it
            // horizontally and then delete

            // get user's name to store file in the user directory
            String user = System.getProperty("user.home");
            String fileName = user + "/webCamPhoto.jpg";
            File newFile = new File(fileName);

            try {
                ImageIO.write(originalImage, "jpg", newFile);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                originalImage = (BufferedImage) ImageIO.read(newFile);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            newFile.delete();
            originalImage = mirrorImage(originalImage);
            icon = scaleBufferedImage(originalImage, originalImageLabel);
            originalImageLabel.setIcon(icon);
        }
    });

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

            if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                try {

                    file = fc.getSelectedFile();
                    File output = new File(file.toString());
                    // check if image already exists
                    if (output.exists()) {
                        int response = JOptionPane.showConfirmDialog(null, //
                                "Do you want to replace the existing file?", //
                                "Confirm", JOptionPane.YES_NO_OPTION, //
                                JOptionPane.QUESTION_MESSAGE);
                        if (response != JOptionPane.YES_OPTION) {
                            return;
                        }
                    }
                    ImageIO.write(toBufferedImage(originalImage), "jpg", output);
                    System.out.println("Your image has been saved in the folder " + file.getPath());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });

    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            btnTakePictureWithWebcam.setVisible(false);
            btnCancel.setVisible(false);
            btnSaveImage.setVisible(false);
            webcam.close();
            panel.setVisible(false);
        }
    });

    urlField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (urlField.getText().length() > 0) {
                String linkNew = urlField.getText();
                getImageFromHttp(linkNew, originalImageLabel);
                originalImage = imageResponses;
            }
        }
    });

    btnAnalyse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            Token computerVisionToken = new Token();
            String computerVisionTokenFileName = "APIToken.txt";

            try {
                computerVisionImageToken = computerVisionToken.getApiToken(computerVisionTokenFileName);
                try {
                    analyse();
                } catch (NullPointerException e1) {
                    // if user clicks on "analyze" button without uploading
                    // image or posts a broken link
                    JOptionPane.showMessageDialog(null, "Please choose an image");
                    e1.printStackTrace();
                }
            } catch (NullPointerException e1) {
                e1.printStackTrace();
            }
        }
    });

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

            // clear labels in case there were results of previous search
            setAllFoundImagesLabelsAndPreviewsToNull();

            System.out.println("==========================================");
            System.out.println("new search");
            System.out.println("==========================================");

            Token bingImageToken = new Token();
            String bingImageTokenFileName = "SearchApiToken.txt";

            bingToken = bingImageToken.getApiToken(bingImageTokenFileName);

            // in case user edited description or tags, update it and
            // replace new line character, spaces and breaks with %20
            text = descriptionField.getText().replace(" ", "%20").replace("\r", "%20").replace("\n", "%20");
            String tagsString = tagsField.getText().replace(" ", "%20").replace("\r", "%20").replace("\n",
                    "%20");

            imageTypeString = imageTypeBox.getSelectedItem().toString();
            sizeTypeString = sizeBox.getSelectedItem().toString();
            licenseTypeString = licenseBox.getSelectedItem().toString();
            safeSearchTypeString = safeSearchBox.getSelectedItem().toString();

            searchParameters = tagsString + text;
            System.out.println("search parameters: " + searchParameters);

            if (searchParameters.length() != 0) {

                // add new thread for searching, so that progress bar and
                // searching could run simultaneously
                Thread t1 = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        progressBar.setVisible(true);
                        searchForSimilarImages(searchParameters, imageTypeString, sizeTypeString,
                                licenseTypeString, safeSearchTypeString);
                    }

                });
                // start searching for similar images in a separate thread
                t1.start();
            } else {
                JOptionPane.showMessageDialog(null,
                        "Please choose first an image to analyse or insert search parameters");
            }
        }
    });

    foundImagesLabel1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel1.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(firstImageUrl);
                }
            }
        }
    });

    foundImagesLabel2.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel2.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(secondImageUrl);
                }
            }
        }
    });

    foundImagesLabel3.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel3.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(thirdImageUrl);
                }
            }
        }
    });

    foundImagesLabel4.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel4.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(fourthImageUrl);
                }
            }
        }
    });

    btnHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // TODO write help
            HelpFrame help = new HelpFrame();
        }
    });
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopFileUploadField.java

public DesktopFileUploadField() {
    fileUploading = AppBeans.get(FileUploadingAPI.NAME);
    messages = AppBeans.get(Messages.NAME);
    exportDisplay = AppBeans.get(ExportDisplay.NAME);

    ComponentsFactory componentsFactory = AppBeans.get(ComponentsFactory.NAME);
    uploadButton = (Button) componentsFactory.createComponent(Button.NAME);
    final JFileChooser fileChooser = new JFileChooser();
    uploadButton.setAction(new AbstractAction("") {
        @Override/* w w w  .  jav a 2s .c  o m*/
        public void actionPerform(Component component) {
            if (fileChooser.showOpenDialog(uploadButton.unwrap(JButton.class)) == JFileChooser.APPROVE_OPTION) {
                uploadFile(fileChooser.getSelectedFile());
            }
        }
    });
    uploadButton.setCaption(messages.getMessage(getClass(), "export.selectFile"));

    initImpl();
}

From source file:edu.ku.brc.specify.tools.LocalizerSearchHelper.java

/**
 * @param baseDir/*from  w w  w. j  a  va2s .  co  m*/
 * @return
 */
public Vector<Pair<String, String>> findOldL10NKeys(final String[] fileNames) {
    initLucene(true);

    //if (srcCodeFilesDir == null)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (srcCodeFilesDir != null) {
            chooser.setSelectedFile(new File(FilenameUtils.getName(srcCodeFilesDir.getAbsolutePath())));
            chooser.setSelectedFile(new File(srcCodeFilesDir.getParent()));
        }

        if (chooser.showOpenDialog(UIRegistry.getMostRecentWindow()) == JFileChooser.APPROVE_OPTION) {
            srcCodeFilesDir = new File(chooser.getSelectedFile().getAbsolutePath());
        } else {
            return null;
        }
    }

    indexSourceFiles();

    Vector<Pair<String, String>> fullNotFoundList = new Vector<Pair<String, String>>();

    try {
        ConversionLogger convLogger = new ConversionLogger();
        convLogger.initialize("resources", "Resources");

        for (String fileName : fileNames) {
            Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>();

            Vector<String> terms = new Vector<String>();

            String propFileName = baseDir.getAbsolutePath() + "/" + fileName;

            File resFile = new File(propFileName + ".properties");
            if (resFile.exists()) {
                List<?> lines = FileUtils.readLines(resFile);
                for (String line : (List<String>) lines) {
                    if (!line.startsWith("#")) {
                        int inx = line.indexOf("=");
                        if (inx > -1) {
                            String[] toks = StringUtils.split(line, "=");
                            if (toks.length > 1) {
                                terms.add(toks[0]);
                            }
                        }
                    }
                }
            } else {
                System.err.println("Doesn't exist: " + resFile.getAbsolutePath());
            }

            String field = "contents";
            QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer);

            for (String term : terms) {
                Query query;
                try {
                    if (term.equals("AND") || term.equals("OR"))
                        continue;

                    query = parser.parse(term);

                    String subTerm = null;
                    int hits = getTotalHits(query, 10);
                    if (hits == 0) {
                        int inx = term.indexOf('.');
                        if (inx > -1) {
                            subTerm = term.substring(inx + 1);
                            hits = getTotalHits(parser.parse(subTerm), 10);

                            if (hits == 0) {
                                int lastInx = term.lastIndexOf('.');
                                if (lastInx > -1 && lastInx != inx) {
                                    subTerm = term.substring(lastInx + 1);
                                    hits = getTotalHits(parser.parse(subTerm), 10);
                                }
                            }
                        }
                    }

                    if (hits == 0 && !term.endsWith("_desc")) {
                        notFoundList.add(new Pair<String, String>(term, subTerm));

                        log.debug("'" + term + "' was not found "
                                + (subTerm != null ? ("SubTerm[" + subTerm + "]") : ""));
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            String fullName = propFileName + ".html";
            TableWriter tblWriter = convLogger.getWriter(FilenameUtils.getName(fullName), propFileName);
            tblWriter.startTable();
            tblWriter.logHdr("Id", "Full Key", "Sub Key");
            int cnt = 1;
            for (Pair<String, String> pair : notFoundList) {
                tblWriter.log(Integer.toString(cnt++), pair.first,
                        pair.second != null ? pair.second : "&nbsp;");
            }
            tblWriter.endTable();

            fullNotFoundList.addAll(notFoundList);

            if (notFoundList.size() > 0 && resFile.exists()) {
                List<String> lines = (List<String>) FileUtils.readLines(resFile);
                Vector<String> linesCache = new Vector<String>();

                for (Pair<String, String> p : notFoundList) {
                    linesCache.clear();
                    linesCache.addAll(lines);

                    int lineInx = 0;
                    for (String line : linesCache) {
                        if (!line.startsWith("#")) {
                            int inx = line.indexOf("=");
                            if (inx > -1) {
                                String[] toks = StringUtils.split(line, "=");
                                if (toks.length > 1) {
                                    if (toks[0].equals(p.first)) {
                                        lines.remove(lineInx);
                                        break;
                                    }
                                }
                            }
                        }
                        lineInx++;
                    }
                }
                FileUtils.writeLines(resFile, linesCache);
            }

        }
        convLogger.closeAll();

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerSearchHelper.class, ex);
        ex.printStackTrace();
    }

    return fullNotFoundList;
}

From source file:de.biomedical_imaging.ij.plot.HistogramPlotter.java

public HistogramPlotter(String title, String xlabel, double[][] data, int numberOfParticles,
        int meanTrackLength, IDatasetCreator datacreator) {

    super(title);
    this.title = title;
    this.xlabel = xlabel;
    this.numberOfParticles = numberOfParticles;
    this.meanTrackLength = meanTrackLength;
    IntervalXYDataset xydataset = datacreator.create(data);
    boolean isbarplot = (datacreator instanceof BarplotDataset);
    txt = new JLabel();
    Font f = new Font("Verdana", Font.PLAIN, 12);
    txt.setFont(f);/*www .  jav  a 2  s  .c  o  m*/

    JFreeChart chart = createChart(xydataset, isbarplot);

    ChartPanel chartPanel = new ChartPanel(chart);

    txt.setText(formatSettingsString());

    main = new JPanel();
    main.setPreferredSize(new java.awt.Dimension(500, 350));
    main.add(chartPanel);
    main.add(txt);
    setContentPane(main);

    setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));

    pack();
    setVisible(true);

    JMenuItem savebutton = ((JMenuItem) chartPanel.getPopupMenu().getComponent(3));
    chartPanel.getPopupMenu().remove(3); // Remove Save button
    //ActionListener al = savebutton.getActionListeners()[0];
    savebutton = new JMenuItem("Save as png");
    //savebutton.removeActionListener(al);
    savebutton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

            try {
                JFileChooser saveFile = new JFileChooser();
                saveFile.setAcceptAllFileFilterUsed(false);
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter("Images", "png"));
                int userSelection = saveFile.showSaveDialog(main);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    BufferedImage bi = ScreenImage.createImage(main);
                    File fileToSave = saveFile.getSelectedFile();
                    String filename = fileToSave.getName();
                    int i = filename.lastIndexOf('.');
                    String suffix = filename.substring(i + 1);
                    String path = fileToSave.getAbsolutePath();
                    if (!(suffix.equals("png"))) {
                        path += ".png";
                    }
                    ScreenImage.writeImage(bi, path);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                IJ.log("" + e.getMessage());
            }

        }
    });
    chartPanel.getPopupMenu().insert(savebutton, 3);

}