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:FileChooserDemo.java

public FileChooserDemo() {
    UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels();
    for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
        try {//from  w  w  w . j  a v a 2  s  .c  om
            Class lnfClass = Class.forName(lafInfo.getClassName());
            LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance());
            if (laf.isSupportedLookAndFeel()) {
                String name = lafInfo.getName();
                supportedLaFs.add(new SupportedLaF(name, laf));
            }
        } catch (Exception e) { // If ANYTHING weird happens, don't add it
            continue;
        }
    }

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

    chooser = new JFileChooser();
    previewer = new FilePreviewer(chooser);

    // Create Custom FileView
    fileView = new ExampleFileView();
    //    fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg")));
    //  fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif")));

    // create a radio listener to listen to option changes
    OptionListener optionListener = new OptionListener();

    // Create options
    openRadioButton = new JRadioButton("Open");
    openRadioButton.setSelected(true);
    openRadioButton.addActionListener(optionListener);

    saveRadioButton = new JRadioButton("Save");
    saveRadioButton.addActionListener(optionListener);

    customButton = new JRadioButton("Custom");
    customButton.addActionListener(optionListener);

    customField = new JTextField(8) {
        public Dimension getMaximumSize() {
            return new Dimension(getPreferredSize().width, getPreferredSize().height);
        }
    };
    customField.setText("Doit");
    customField.setAlignmentY(JComponent.TOP_ALIGNMENT);
    customField.setEnabled(false);
    customField.addActionListener(optionListener);

    ButtonGroup group1 = new ButtonGroup();
    group1.add(openRadioButton);
    group1.add(saveRadioButton);
    group1.add(customButton);

    // filter buttons
    showAllFilesFilterCheckBox = new JCheckBox("Show \"All Files\" Filter");
    showAllFilesFilterCheckBox.addActionListener(optionListener);
    showAllFilesFilterCheckBox.setSelected(true);

    showImageFilesFilterCheckBox = new JCheckBox("Show JPG and GIF Filters");
    showImageFilesFilterCheckBox.addActionListener(optionListener);
    showImageFilesFilterCheckBox.setSelected(false);

    accessoryCheckBox = new JCheckBox("Show Preview");
    accessoryCheckBox.addActionListener(optionListener);
    accessoryCheckBox.setSelected(false);

    // more options
    setHiddenCheckBox = new JCheckBox("Show Hidden Files");
    setHiddenCheckBox.addActionListener(optionListener);

    showFullDescriptionCheckBox = new JCheckBox("With File Extensions");
    showFullDescriptionCheckBox.addActionListener(optionListener);
    showFullDescriptionCheckBox.setSelected(true);
    showFullDescriptionCheckBox.setEnabled(false);

    useFileViewCheckBox = new JCheckBox("Use FileView");
    useFileViewCheckBox.addActionListener(optionListener);
    useFileViewCheckBox.setSelected(false);

    useEmbedInWizardCheckBox = new JCheckBox("Embed in Wizard");
    useEmbedInWizardCheckBox.addActionListener(optionListener);
    useEmbedInWizardCheckBox.setSelected(false);

    useControlsCheckBox = new JCheckBox("Show Control Buttons");
    useControlsCheckBox.addActionListener(optionListener);
    useControlsCheckBox.setSelected(true);

    enableDragCheckBox = new JCheckBox("Enable Dragging");
    enableDragCheckBox.addActionListener(optionListener);

    // File or Directory chooser options
    ButtonGroup group3 = new ButtonGroup();
    justFilesRadioButton = new JRadioButton("Just Select Files");
    justFilesRadioButton.setSelected(true);
    group3.add(justFilesRadioButton);
    justFilesRadioButton.addActionListener(optionListener);

    justDirectoriesRadioButton = new JRadioButton("Just Select Directories");
    group3.add(justDirectoriesRadioButton);
    justDirectoriesRadioButton.addActionListener(optionListener);

    bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories");
    group3.add(bothFilesAndDirectoriesRadioButton);
    bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);

    singleSelectionRadioButton = new JRadioButton("Single Selection", true);
    singleSelectionRadioButton.addActionListener(optionListener);

    multiSelectionRadioButton = new JRadioButton("Multi Selection");
    multiSelectionRadioButton.addActionListener(optionListener);

    ButtonGroup group4 = new ButtonGroup();
    group4.add(singleSelectionRadioButton);
    group4.add(multiSelectionRadioButton);

    // Create show button
    showButton = new JButton("Show FileChooser");
    showButton.addActionListener(this);
    showButton.setMnemonic('s');

    // Create laf combo box

    lafComboBox = new JComboBox(supportedLaFs);
    lafComboBox.setEditable(false);
    lafComboBox.addActionListener(optionListener);

    // ********************************************************
    // ******************** Dialog Type ***********************
    // ********************************************************
    JPanel control1 = new InsetPanel(insets);
    control1.setBorder(BorderFactory.createTitledBorder("Dialog Type"));

    control1.setLayout(new BoxLayout(control1, BoxLayout.Y_AXIS));
    control1.add(Box.createRigidArea(vpad20));
    control1.add(openRadioButton);
    control1.add(Box.createRigidArea(vpad7));
    control1.add(saveRadioButton);
    control1.add(Box.createRigidArea(vpad7));
    control1.add(customButton);
    control1.add(Box.createRigidArea(vpad4));
    JPanel fieldWrapper = new JPanel();
    fieldWrapper.setLayout(new BoxLayout(fieldWrapper, BoxLayout.X_AXIS));
    fieldWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);
    fieldWrapper.add(Box.createRigidArea(hpad10));
    fieldWrapper.add(Box.createRigidArea(hpad10));
    fieldWrapper.add(customField);
    control1.add(fieldWrapper);
    control1.add(Box.createRigidArea(vpad20));
    control1.add(Box.createGlue());

    // ********************************************************
    // ***************** Filter Controls **********************
    // ********************************************************
    JPanel control2 = new InsetPanel(insets);
    control2.setBorder(BorderFactory.createTitledBorder("Filter Controls"));
    control2.setLayout(new BoxLayout(control2, BoxLayout.Y_AXIS));
    control2.add(Box.createRigidArea(vpad20));
    control2.add(showAllFilesFilterCheckBox);
    control2.add(Box.createRigidArea(vpad7));
    control2.add(showImageFilesFilterCheckBox);
    control2.add(Box.createRigidArea(vpad4));
    JPanel checkWrapper = new JPanel();
    checkWrapper.setLayout(new BoxLayout(checkWrapper, BoxLayout.X_AXIS));
    checkWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);
    checkWrapper.add(Box.createRigidArea(hpad10));
    checkWrapper.add(Box.createRigidArea(hpad10));
    checkWrapper.add(showFullDescriptionCheckBox);
    control2.add(checkWrapper);
    control2.add(Box.createRigidArea(vpad20));
    control2.add(Box.createGlue());

    // ********************************************************
    // ****************** Display Options *********************
    // ********************************************************
    JPanel control3 = new InsetPanel(insets);
    control3.setBorder(BorderFactory.createTitledBorder("Display Options"));
    control3.setLayout(new BoxLayout(control3, BoxLayout.Y_AXIS));
    control3.add(Box.createRigidArea(vpad20));
    control3.add(setHiddenCheckBox);
    control3.add(Box.createRigidArea(vpad7));
    control3.add(useFileViewCheckBox);
    control3.add(Box.createRigidArea(vpad7));
    control3.add(accessoryCheckBox);
    control3.add(Box.createRigidArea(vpad7));
    control3.add(useEmbedInWizardCheckBox);
    control3.add(Box.createRigidArea(vpad7));
    control3.add(useControlsCheckBox);
    control3.add(Box.createRigidArea(vpad7));
    control3.add(enableDragCheckBox);
    control3.add(Box.createRigidArea(vpad20));
    control3.add(Box.createGlue());

    // ********************************************************
    // ************* File & Directory Options *****************
    // ********************************************************
    JPanel control4 = new InsetPanel(insets);
    control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options"));
    control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
    control4.add(Box.createRigidArea(vpad20));
    control4.add(justFilesRadioButton);
    control4.add(Box.createRigidArea(vpad7));
    control4.add(justDirectoriesRadioButton);
    control4.add(Box.createRigidArea(vpad7));
    control4.add(bothFilesAndDirectoriesRadioButton);
    control4.add(Box.createRigidArea(vpad20));
    control4.add(singleSelectionRadioButton);
    control4.add(Box.createRigidArea(vpad7));
    control4.add(multiSelectionRadioButton);
    control4.add(Box.createRigidArea(vpad20));
    control4.add(Box.createGlue());

    // ********************************************************
    // **************** Look & Feel Switch ********************
    // ********************************************************
    JPanel panel = new JPanel();
    panel.add(new JLabel("Look and Feel: "));
    panel.add(lafComboBox);
    panel.add(showButton);

    // ********************************************************
    // ****************** Wrap 'em all up *********************
    // ********************************************************
    JPanel wrapper = new JPanel();
    wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.X_AXIS));

    add(Box.createRigidArea(vpad20));

    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(control1);
    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(control2);
    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(control3);
    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(control4);
    wrapper.add(Box.createRigidArea(hpad10));
    wrapper.add(Box.createRigidArea(hpad10));

    add(wrapper);
    add(Box.createRigidArea(vpad20));
    add(panel);
    add(Box.createRigidArea(vpad20));
}

From source file:com.sf.energy.transfer.form.DataConfiguration.java

/**
 * ??/*  ww w.j  av  a  2 s  . co  m*/
 * @param evt ?
 */
private void scanActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fc = new JFileChooser();
    File directory = new File(dir);
    // ??
    fc.setCurrentDirectory(directory);
    fc.setDialogTitle("");
    // 
    FileNameExtensionFilter filter1 = new FileNameExtensionFilter(".xls", "xls");
    fc.addChoosableFileFilter(filter1);
    FileNameExtensionFilter filter2 = new FileNameExtensionFilter(".dmp", "dmp");
    fc.addChoosableFileFilter(filter1);
    // 
    fc.setFileFilter(fc.getAcceptAllFileFilter());
    int intRetVal = fc.showOpenDialog(new JFrame());
    // ?
    if (intRetVal == JFileChooser.APPROVE_OPTION) {
        // ?
        dir = fc.getSelectedFile().getPath();
        // 
        filePath.setText(dir);
    }

}

From source file:edu.ku.brc.ui.ImageDisplay.java

/**
 * // www  .j a va2s.co  m
 */
protected void selectNewImage() {
    String oldURL = this.url;
    synchronized (this) {
        if (chooser == null) {
            //      XXX Need to add a filter for just images
            chooser = new JFileChooser();
        }
    }

    int returnVal = chooser.showOpenDialog(UIRegistry.getTopWindow());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(chooser.getSelectedFile().getAbsolutePath());
        try {
            setImage(ImageIO.read(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = file.getAbsolutePath();
        repaint();
    }

    firePropertyChange("imageURL", oldURL, url);
}

From source file:com.smart.aqimonitor.client.AqiSettingDialog.java

/**
 * Create the dialog./*from   w  w  w .j  a v  a  2  s.  c o m*/
 */
public AqiSettingDialog(Frame owner, final AbstractAqiParser aqiParser) {
    super(owner);
    this.aqiParser = aqiParser;
    setTitle("\u8BBE\u7F6E");
    setResizable(false);
    setBounds(100, 100, 450, 135);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    GridBagLayout gbl_contentPanel = new GridBagLayout();
    gbl_contentPanel.columnWidths = new int[] { 33, 48, 66, 41, 48, 66, 0, 0 };
    gbl_contentPanel.rowHeights = new int[] { 21, 0, 0 };
    gbl_contentPanel.columnWeights = new double[] { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_contentPanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    contentPanel.setLayout(gbl_contentPanel);
    {
        JLabel lblRetryTimes = new JLabel("\u91CD\u8BD5\u6B21\u6570\uFF1A");
        GridBagConstraints gbc_lblRetryTimes = new GridBagConstraints();
        gbc_lblRetryTimes.anchor = GridBagConstraints.WEST;
        gbc_lblRetryTimes.insets = new Insets(0, 0, 5, 5);
        gbc_lblRetryTimes.gridx = 1;
        gbc_lblRetryTimes.gridy = 0;
        contentPanel.add(lblRetryTimes, gbc_lblRetryTimes);
    }
    {
        tfRetryTimes = new JTextField();
        tfRetryTimes.setPreferredSize(new Dimension(6, 29));
        tfRetryTimes.setMinimumSize(new Dimension(60, 29));
        GridBagConstraints gbc_tfRetryTimes = new GridBagConstraints();
        gbc_tfRetryTimes.anchor = GridBagConstraints.NORTHWEST;
        gbc_tfRetryTimes.insets = new Insets(0, 0, 5, 5);
        gbc_tfRetryTimes.gridx = 2;
        gbc_tfRetryTimes.gridy = 0;
        contentPanel.add(tfRetryTimes, gbc_tfRetryTimes);
        tfRetryTimes.setColumns(10);
    }
    {
        JLabel lblRetryGap = new JLabel("\u91CD\u8BD5\u95F4\u9694\uFF1A");
        GridBagConstraints gbc_lblRetryGap = new GridBagConstraints();
        gbc_lblRetryGap.anchor = GridBagConstraints.WEST;
        gbc_lblRetryGap.insets = new Insets(0, 0, 5, 5);
        gbc_lblRetryGap.gridx = 4;
        gbc_lblRetryGap.gridy = 0;
        contentPanel.add(lblRetryGap, gbc_lblRetryGap);
    }
    {
        tfRetryGap = new JTextField();
        tfRetryGap.setMinimumSize(new Dimension(60, 29));
        tfRetryGap.setPreferredSize(new Dimension(60, 29));
        GridBagConstraints gbc_tfRetryGap = new GridBagConstraints();
        gbc_tfRetryGap.insets = new Insets(0, 0, 5, 5);
        gbc_tfRetryGap.anchor = GridBagConstraints.NORTHWEST;
        gbc_tfRetryGap.gridx = 5;
        gbc_tfRetryGap.gridy = 0;
        contentPanel.add(tfRetryGap, gbc_tfRetryGap);
        tfRetryGap.setColumns(10);
    }
    {
        JLabel label = new JLabel("\u5206\u949F");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.insets = new Insets(0, 0, 5, 0);
        gbc_label.gridx = 6;
        gbc_label.gridy = 0;
        contentPanel.add(label, gbc_label);
    }
    {
        JLabel lblExportPath = new JLabel("\u8F93\u51FA\u8DEF\u5F84\uFF1A");
        GridBagConstraints gbc_lblExportPath = new GridBagConstraints();
        gbc_lblExportPath.anchor = GridBagConstraints.EAST;
        gbc_lblExportPath.insets = new Insets(0, 0, 0, 5);
        gbc_lblExportPath.gridx = 1;
        gbc_lblExportPath.gridy = 1;
        contentPanel.add(lblExportPath, gbc_lblExportPath);
    }
    {
        tfExportPath = new JTextField();
        tfExportPath.setEditable(false);
        tfExportPath.setPreferredSize(new Dimension(180, 29));
        tfExportPath.setMinimumSize(new Dimension(180, 29));
        GridBagConstraints gbc_tfExportPath = new GridBagConstraints();
        gbc_tfExportPath.gridwidth = 4;
        gbc_tfExportPath.insets = new Insets(0, 0, 0, 5);
        gbc_tfExportPath.fill = GridBagConstraints.HORIZONTAL;
        gbc_tfExportPath.gridx = 2;
        gbc_tfExportPath.gridy = 1;
        contentPanel.add(tfExportPath, gbc_tfExportPath);
        tfExportPath.setColumns(10);
    }
    {
        JButton button = new JButton("...");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fDialog = new JFileChooser(); // 
                fDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = fDialog.showOpenDialog(contentPanel);
                if (result == JFileChooser.APPROVE_OPTION) {
                    tfExportPath.setText(fDialog.getSelectedFile().getAbsolutePath());
                }
            }
        });
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.gridx = 6;
        gbc_button.gridy = 1;
        contentPanel.add(button, gbc_button);
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton okButton = new JButton("\u786E\u5B9A");
            okButton.setName("settingOk");
            okButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {

                    String retryTimes = tfRetryTimes.getText();
                    if (StringUtils.isEmpty(retryTimes) || !isNumeric(retryTimes)) {
                        JOptionPane.showMessageDialog(contentPanel, "", "",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    String retryGap = tfRetryGap.getText();
                    if (StringUtils.isEmpty(retryGap) || !isNumeric(retryGap)) {
                        JOptionPane.showMessageDialog(contentPanel, "", "",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    String exportPath = tfExportPath.getText();
                    if (StringUtils.isEmpty(exportPath)) {
                        JOptionPane.showMessageDialog(contentPanel, "", "",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    File testFile = new File(exportPath);
                    if (!testFile.exists()) {
                        JOptionPane.showMessageDialog(contentPanel, "", "",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    props.put("query.retryTimes", retryTimes);
                    props.put("query.retryGap", retryGap);
                    props.put("result.path", exportPath);

                    try {
                        props.store(new FileOutputStream(propertiesResource.getFile()), "");
                        aqiParser.setRetryTimes(Integer.parseInt(retryTimes));
                        aqiParser.setRetryGap(Integer.parseInt(retryGap));
                        aqiParser.setFilePath(exportPath);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    } finally {
                        dispose();
                    }
                }
            });
            okButton.setActionCommand("OK");
            buttonPane.add(okButton);
            getRootPane().setDefaultButton(okButton);
        }
        {
            JButton cancelButton = new JButton("\u53D6\u6D88");
            cancelButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
            cancelButton.setActionCommand("Cancel");
            buttonPane.add(cancelButton);
        }
    }
}

From source file:com.akman.excel.view.frmSelectImage.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectImageActionPerformed
{//GEN-HEADEREND:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);/*from   w w  w  .  ja  v  a2s. com*/

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }

        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileName = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);

        txtPath.setText(fileName);

        try {

            File images = new File(fileName);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:com.strath.view.MainGUI.java

private void projectSelectMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_projectSelectMouseReleased
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    int returnValue = chooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File directory = chooser.getSelectedFile();
        String[] extensions = new String[1];
        extensions[0] = "java";
        selectedProject = listFiles(directory, extensions, true);
        isProjectSet = true;/*from www  . ja va2  s  .co  m*/
    }
}

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

@Override
public void start() {
    startDate = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    setPercentComplete(0);//from  w ww.jav  a2  s. c om
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Selecting file to check.");
    String rawOCR = ""; // to hold unparsed ocr output from unit tray label
    //Create a file chooser
    final JFileChooser fileChooser = new JFileChooser();
    if (Singleton.getSingletonInstance().getProperties().getProperties()
            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
        fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
    }
    //FileNameExtensionFilter filter = new FileNameExtensionFilter("TIFF Images", "tif", "tiff");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "tif", "tiff", "jpg", "jpeg",
            "png");
    fileChooser.setFileFilter(filter);
    int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
    setPercentComplete(10);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Scanning file for barcode.");
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File fileToCheck = fileChooser.getSelectedFile();
        Singleton.getSingletonInstance().getProperties().getProperties()
                .setProperty(ImageCaptureProperties.KEY_LASTPATH, fileToCheck.getPath());
        String filename = fileToCheck.getName();
        log.debug("Selected file " + filename + " to scan for barcodes");
        CandidateImageFile.debugCheckHeightWidth(fileToCheck);

        // scan selected file
        PositionTemplate defaultTemplate = null;
        // Figure out which template to use.
        DefaultPositionTemplateDetector detector = new DefaultPositionTemplateDetector();
        String template = "";
        try {
            template = detector.detectTemplateForImage(fileToCheck);
        } catch (UnreadableFileException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
        setPercentComplete(20);
        try {
            defaultTemplate = new PositionTemplate(template);
            log.debug("Set template to: " + defaultTemplate.getTemplateId());
        } catch (NoSuchTemplateException e1) {
            try {
                defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT);
                log.error("Template not recongised, reset template to: " + defaultTemplate.getTemplateId());
            } catch (Exception e2) {
                // We shouldn't end up here - we just asked for the default template by its constant.
                log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT");
                log.trace(e2);
                ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR);
            }
        }
        // TODO: Store the template id for this image with the other image metadata so
        // that we don't have to check again.

        CandidateImageFile scannableFile;
        try {
            scannableFile = new CandidateImageFile(fileToCheck, defaultTemplate);

            String barcode = scannableFile.getBarcodeTextAtFoundTemplate();
            if (scannableFile.getCatalogNumberBarcodeStatus() != CandidateImageFile.RESULT_BARCODE_SCANNED) {
                log.error("Error scanning for barcode: " + barcode);
                barcode = "";
            }
            String exifComment = scannableFile.getExifUserCommentText();
            if (barcode.equals("")
                    && Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment)) {
                // There should be a template for this image, and it shouldn't be the TEMPLATE_NO_COMPONENT_PARTS 
                if (defaultTemplate.getTemplateId().equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) {
                    try {
                        // This will give us a shot at OCR of the text and display of the image parts.
                        defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT);
                        log.error("Barcode not recongised, but exif contains barcode, reset template to: "
                                + defaultTemplate.getTemplateId());
                    } catch (Exception e2) {
                        // We shouldn't end up here - we just asked for the default template by its constant.
                        log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT");
                        log.trace(e2);
                        ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR);
                    }
                }
            }

            log.debug("With template:" + defaultTemplate.getTemplateId());
            log.debug("Barcode=" + barcode);

            setPercentComplete(30);

            String warning = "";
            if (Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) {
                if (!barcode.equals(exifComment)) {
                    warning = "Warning: non-matching QR code barcode and exif Comment";
                    System.out.println(warning);
                }
            }

            Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Loading image.");

            ImageDisplayFrame resultFrame = new ImageDisplayFrame();

            if (Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) {
                resultFrame.setBarcode("QR=" + barcode + " Comment=" + exifComment + " " + warning);
            } else {
                resultFrame.setBarcode("QR=" + barcode);
            }

            try {
                resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null);
            } catch (ImageLoadException e2) {
                System.out.println("Error loading image file.");
                System.out.println(e2.getMessage());
            } catch (BadTemplateException e2) {
                System.out.println("Template doesn't match image file.");
                System.out.println(e2.getMessage());
                try {
                    try {
                        try {
                            template = detector.detectTemplateForImage(fileToCheck);
                        } catch (UnreadableFileException e3) {
                            // TODO Auto-generated catch block
                            e3.printStackTrace();
                        }
                        defaultTemplate = new PositionTemplate(template);
                    } catch (NoSuchTemplateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null);
                } catch (ImageLoadException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BadTemplateException e) {
                    System.out.println("Template doesn't match image file.");
                    System.out.println(e2.getMessage());
                }
            }

            UnitTrayLabel labelRead = null;
            try {
                // Read unitTrayLabelBarcode, failover to OCR and parse UnitTray Label
                rawOCR = "";
                labelRead = scannableFile.getTaxonLabelQRText(defaultTemplate);
                if (labelRead == null) {
                    try {
                        labelRead = scannableFile.getTaxonLabelQRText(new PositionTemplate("Test template 2"));
                    } catch (NoSuchTemplateException e1) {
                        try {
                            labelRead = scannableFile
                                    .getTaxonLabelQRText(new PositionTemplate("Small template 2"));
                        } catch (NoSuchTemplateException e2) {
                            log.error("None of " + defaultTemplate.getName()
                                    + " Test template 2 or Small template 2 were found");
                        }
                    }
                } else {
                    log.debug("Translated UnitTrayBarcode to: " + labelRead.toJSONString());
                }
                if (labelRead != null) {
                    rawOCR = labelRead.toJSONString();
                } else {
                    log.debug("Failing over to OCR with tesseract");
                    rawOCR = scannableFile.getLabelOCRText(defaultTemplate);
                }
                log.debug(rawOCR);
                resultFrame.setRawOCRLabel(rawOCR);
                setPercentComplete(40);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

            setPercentComplete(50);

            resultFrame.pack();
            resultFrame.setVisible(true);
            resultFrame.centerSpecimen();
            resultFrame.center();
            setPercentComplete(60);

            if (persist) {
                // Check that fileToCheck is within imagebase.
                if (!ImageCaptureProperties.isInPathBelowBase(fileToCheck)) {
                    String base = Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                    log.error("Tried to scan file (" + fileToCheck.getPath()
                            + ") outside of base image directory (" + base + ")");
                    throw new UnreadableFileException(
                            "Can't scan and database files outside of base image directory (" + base + ")");
                }

                String state = WorkFlowStatus.STAGE_0;
                Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Connecting to database.");
                // try to parse the raw OCR               
                TaxonNameReturner parser = null;
                if (labelRead != null) {
                    rawOCR = labelRead.toJSONString();
                    state = WorkFlowStatus.STAGE_1;
                    parser = (TaxonNameReturner) labelRead;
                } else {
                    log.debug("Failing over to OCR with tesseract");
                    rawOCR = scannableFile.getLabelOCRText(defaultTemplate);
                    state = WorkFlowStatus.STAGE_0;
                    parser = new UnitTrayLabelParser(rawOCR);
                }

                // Case 1: This is an image of papers associated with a container (a unit tray or a box).
                // This case can be identified by there being no barcode data associated with the image.
                // Action: 
                // A) Check the exifComment to see what metadata is there, if blank, bring up a dialog.
                // Options: A drawer, for which number is captured.  A unit tray, capture ?????????.  A specimen
                // where barcode wasn't read, allow capture of barcode and treat as Case 2.
                // B) Create an image record and store the image metadata (with a null specimen_id).  

                boolean isSpecimenImage = false;
                boolean isDrawerImage = false;
                // Test: is exifComment a barcode:
                if (Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment)
                        || Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) {
                    isSpecimenImage = true;
                    System.out.println("Specimen Image");
                } else {
                    if (exifComment.matches(Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_REGEX_DRAWERNUMBER))) {
                        isDrawerImage = true;
                        System.out.println("Drawer Image");
                    } else {
                        // Ask.
                        System.out.println("Need to ask.");
                        WhatsThisImageDialog askDialog = new WhatsThisImageDialog(resultFrame, fileToCheck);
                        askDialog.setVisible(true);
                        if (askDialog.isSpecimen()) {
                            isSpecimenImage = true;
                            exifComment = askDialog.getBarcode();
                        }
                        if (askDialog.isDrawerImage()) {
                            isDrawerImage = true;
                            exifComment = askDialog.getDrawerNumber();
                        }
                    }
                }

                // applies to both cases.
                ICImageLifeCycle imageCont = new ICImageLifeCycle();
                ICImage tryMe = new ICImage();
                tryMe.setFilename(filename);
                //String path = fileToCheck.getParentFile().getPath();
                String path = ImageCaptureProperties.getPathBelowBase(fileToCheck);
                //String[] bits = rawOCR.split(":");
                List<ICImage> matches = imageCont.findByExample(tryMe);

                // Case 2: This is an image of a specimen and associated labels or an image assocated with 
                // a specimen with the specimen's barcode label in the image.
                // This case can be identified by there being a barcode in a templated position or there 
                // being a barcode in the exif comment tag.  
                // Action: 
                // A) Check if a specimen record exists, if not, create one from the barcode and OCR data.
                // B) Create an image record and store the image metadata.

                // Handle a potential failure case, existing image record without a linked specimen, but which 
                // should have one.
                if (matches.size() == 1 && isSpecimenImage) {
                    ICImage existing = imageCont.findById(matches.get(0).getImageId());
                    if (existing.getSpecimen() == null) {
                        // If the existing image record has no attached specimen, delete it. 
                        // We will create it again from tryMe.
                        try {
                            Singleton.getSingletonInstance().getMainFrame()
                                    .setStatusMessage("Removing existing unlinked image record.");
                            imageCont.delete(existing);
                            matches.remove(0);
                        } catch (SaveFailedException e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }

                if (matches.size() == 0) {
                    String rawBarcode = barcode;
                    if (isSpecimenImage) {
                        Singleton.getSingletonInstance().getMainFrame()
                                .setStatusMessage("Creating new specimen record.");
                        Specimen s = new Specimen();
                        if ((!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode))
                                && Singleton.getSingletonInstance().getBarcodeMatcher()
                                        .matchesPattern(exifComment)) {
                            s.setBarcode(exifComment);
                            barcode = exifComment;
                        } else {
                            if (!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) {
                                // Won't be able to save the specimen record if we end up here.
                                log.error(
                                        "Neither exifComment nor QR Code barcode match the expected pattern for a barcode, but isSpecimenImage got set to true.");
                            }
                            s.setBarcode(barcode);
                        }
                        s.setWorkFlowStatus(state);
                        if (!state.equals(WorkFlowStatus.STAGE_0)) {
                            s.setFamily(parser.getFamily());
                            s.setSubfamily(parser.getSubfamily());
                            s.setTribe(parser.getTribe());
                        } else {
                            s.setFamily("");
                            // Look up likely matches for the OCR of the higher taxa in the HigherTaxon authority file.
                            HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle();
                            if (parser.getTribe().trim().equals("")) {
                                if (hls.isMatched(parser.getFamily(), parser.getSubfamily())) {
                                    // If there is a match, use it.
                                    String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily());
                                    s.setFamily(higher[0]);
                                    s.setSubfamily(higher[1]);
                                } else {
                                    // otherwise use the raw OCR output.
                                    s.setFamily(parser.getFamily());
                                    s.setSubfamily(parser.getSubfamily());
                                }
                                s.setTribe("");
                            } else {
                                if (hls.isMatched(parser.getFamily(), parser.getSubfamily(),
                                        parser.getTribe())) {
                                    String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily(),
                                            parser.getTribe());
                                    s.setFamily(higher[0]);
                                    s.setSubfamily(higher[1]);
                                    s.setTribe(higher[2]);
                                } else {
                                    s.setFamily(parser.getFamily());
                                    s.setSubfamily(parser.getSubfamily());
                                    s.setTribe(parser.getTribe());
                                }
                            }
                            if (!parser.getFamily().equals("")) {
                                // check family against database (with a soundex match)
                                String match = hls.findMatch(parser.getFamily());
                                if (match != null && !match.trim().equals("")) {
                                    s.setFamily(match);
                                }
                            }
                        }
                        // trim family to fit (in case multiple parts of taxon name weren't parsed
                        // and got concatenated into family field.
                        if (s.getFamily().length() > 40) {
                            s.setFamily(s.getFamily().substring(0, 40));
                        }

                        s.setGenus(parser.getGenus());
                        s.setSpecificEpithet(parser.getSpecificEpithet());
                        s.setSubspecificEpithet(parser.getSubspecificEpithet());
                        s.setInfraspecificEpithet(parser.getInfraspecificEpithet());
                        s.setInfraspecificRank(parser.getInfraspecificRank());
                        s.setAuthorship(parser.getAuthorship());
                        s.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                        s.setCollection(((CollectionReturner) parser).getCollection());
                        s.setCreatingPath(ImageCaptureProperties.getPathBelowBase(fileToCheck));
                        s.setCreatingFilename(fileToCheck.getName());
                        if (parser.getIdentifiedBy() != null && parser.getIdentifiedBy().length() > 0) {
                            s.setIdentifiedBy(parser.getIdentifiedBy());
                        }
                        log.debug(s.getCollection());

                        // TODO: non-general workflows

                        // ********* Special Cases **********
                        if (s.getWorkFlowStatus().equals(WorkFlowStatus.STAGE_0)) {
                            // ***** Special case, images in ent-formicidae 
                            //       get family set to Formicidae if in state OCR.
                            if (path.contains("formicidae")) {
                                s.setFamily("Formicidae");
                            }
                        }
                        s.setLocationInCollection(LocationInCollection.getDefaultLocation());
                        if (s.getFamily().equals("Formicidae")) {
                            // ***** Special case, families in Formicidae are in Ant collection
                            s.setLocationInCollection(LocationInCollection.GENERALANT);
                        }
                        // ********* End Special Cases **********

                        s.setCreatedBy(ImageCaptureApp.APP_NAME + " " + ImageCaptureApp.APP_VERSION);
                        SpecimenLifeCycle sh = new SpecimenLifeCycle();
                        try {
                            sh.persist(s);
                            s.attachNewPart();
                        } catch (SpecimenExistsException e) {
                            log.debug(e);
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    filename + " " + barcode + " \n" + e.getMessage(),
                                    "Specimen Exists, linking Image to existing record.",
                                    JOptionPane.ERROR_MESSAGE);
                            List<Specimen> checkResult = sh.findByBarcode(barcode);
                            if (checkResult.size() == 1) {
                                s = checkResult.get(0);
                            }
                        } catch (SaveFailedException e) {
                            // Couldn't save, but for some reason other than the
                            // specimen record already existing.
                            log.debug(e);
                            try {
                                List<Specimen> checkResult = sh.findByBarcode(barcode);
                                if (checkResult.size() == 1) {
                                    s = checkResult.get(0);
                                }
                                // Drawer number with length limit (and specimen that fails to save at over this length makes
                                // a good canary for labels that parse very badly.
                                String badParse = "";
                                if (((DrawerNameReturner) parser).getDrawerNumber().length() > MetadataRetriever
                                        .getFieldLength(Specimen.class, "DrawerNumber")) {
                                    badParse = "Parsing problem. \nDrawer number is too long: "
                                            + s.getDrawerNumber() + "\n";
                                }
                                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                        filename + " " + barcode + " \n" + badParse + e.getMessage(),
                                        "Badly parsed OCR", JOptionPane.ERROR_MESSAGE);
                            } catch (Exception err) {
                                log.error(e);
                                log.error(err);
                                // TODO: Add a general error handling/inform user class.
                                // Cause of exception is not likely to be drawer number now that drawer number
                                // length is enforced in Specimen.setDrawerNumber, but the text returned by the parser
                                // might indicate very poor OCR as a cause.
                                String badParse = ((DrawerNameReturner) parser).getDrawerNumber();
                                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                        filename + " " + barcode + "\n" + badParse + e.getMessage(),
                                        "Save Failed", JOptionPane.ERROR_MESSAGE);
                                s = null;
                            }
                        }
                        setPercentComplete(70);
                        if (s != null) {
                            tryMe.setSpecimen(s);
                        }
                    }
                    tryMe.setRawBarcode(rawBarcode);
                    if (isDrawerImage) {
                        tryMe.setDrawerNumber(exifComment);
                    } else {
                        tryMe.setRawExifBarcode(exifComment);
                        tryMe.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                    }
                    tryMe.setRawOcr(rawOCR);
                    tryMe.setTemplateId(defaultTemplate.getTemplateId());
                    tryMe.setPath(path);
                    if (tryMe.getMd5sum() == null || tryMe.getMd5sum().length() == 0) {
                        try {
                            tryMe.setMd5sum(DigestUtils.md5Hex(new FileInputStream(fileToCheck)));
                        } catch (FileNotFoundException e) {
                            log.error(e.getMessage());
                        } catch (IOException e) {
                            log.error(e.getMessage());
                        }
                    }
                    try {
                        imageCont.persist(tryMe);
                    } catch (SaveFailedException e) {
                        // TODO Auto-generated catch block
                        log.error(e.getMessage());
                        e.printStackTrace();
                    }

                    setPercentComplete(80);
                    if (isSpecimenImage) {
                        SpecimenControler controler = null;
                        try {
                            controler = new SpecimenControler(tryMe.getSpecimen());
                            controler.setTargetFrame(resultFrame);
                        } catch (NoSuchRecordException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(tryMe.getSpecimen(),
                                controler);
                        resultFrame.addWest((JPanel) sPane);
                        if (!tryMe.getRawBarcode().equals(tryMe.getRawExifBarcode())) {
                            if (Singleton.getSingletonInstance().getProperties().getProperties()
                                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE)
                                    .equals("true")) {
                                // If so configured, warn about missmatch 
                                sPane.setWarning(
                                        "Warning: Scanned Image has missmatch between barcode and comment.");
                            }
                        }
                    }
                    resultFrame.center();
                } else {
                    // found one or more matching image records.
                    setPercentComplete(80);
                    Singleton.getSingletonInstance().getMainFrame()
                            .setStatusMessage("Loading existing image record.");
                    ICImage existing = imageCont.findById(matches.get(0).getImageId());
                    System.out.println(existing.getRawBarcode());
                    existing.setRawBarcode(barcode);
                    if (isDrawerImage) {
                        existing.setDrawerNumber(exifComment);
                    } else {
                        existing.setRawExifBarcode(exifComment);
                    }
                    existing.setTemplateId(defaultTemplate.getTemplateId());
                    if (existing.getPath() == null || existing.getPath().equals("")) {
                        existing.setPath(path);
                    }
                    if (existing.getDrawerNumber() == null || existing.getDrawerNumber().equals("")) {
                        existing.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber());
                    }
                    try {
                        imageCont.attachDirty(existing);
                    } catch (SaveFailedException e) {
                        // TODO Auto-generated catch block
                        log.error(e.getMessage());
                        e.printStackTrace();
                    }
                    if (isSpecimenImage) {
                        SpecimenControler controler = null;
                        try {
                            controler = new SpecimenControler(existing.getSpecimen());
                            controler.setTargetFrame(resultFrame);
                            System.out.println(existing.getSpecimen().getBarcode());
                        } catch (NullPointerException e1) {
                            log.debug("Specimen barcode not set");
                        } catch (NoSuchRecordException e) {
                            // Failure case 
                            log.error(e.getMessage(), e);
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    filename + " " + barcode + "\n"
                                            + "Existing Image record with no Specimen Record. "
                                            + e.getMessage(),
                                    "Save Failed.", JOptionPane.ERROR_MESSAGE);
                        }
                        SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(existing.getSpecimen(),
                                controler);
                        resultFrame.addWest((JPanel) sPane);
                        resultFrame.center();
                        resultFrame.setActiveTab(ImageDisplayFrame.TAB_LABELS);
                        resultFrame.fitPinLabels();
                        if (!existing.getRawBarcode().equals(existing.getRawExifBarcode())) {
                            if (Singleton.getSingletonInstance().getProperties().getProperties()
                                    .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE)
                                    .equals("true")) {
                                sPane.setWarning(
                                        "Warning: Scanned Image has missmatch between barcode and comment.");
                            }
                        }
                    }
                    setPercentComplete(90);
                }
            }
        } catch (UnreadableFileException e1) {
            log.error("Unable to read selected file." + e1.getMessage());
        } catch (OCRReadException e) {
            log.error("Failed to OCR file." + e.getMessage());
        }
    } else {
        System.out.println("No file selected from dialog.");
    }
    setPercentComplete(100);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage("");
    SpecimenLifeCycle sls = new SpecimenLifeCycle();
    Singleton.getSingletonInstance().getMainFrame().setCount(sls.findSpecimenCount());
    Singleton.getSingletonInstance().getJobList().removeJob((RunnableJob) this);
}

From source file:e3fraud.gui.MainWindow.java

public MainWindow() {
    super(new BorderLayout(5, 5));

    extended = false;/*  w  w  w.j  ava2s . co  m*/

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(10, 50);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    logScrollPane = new JScrollPane(log);
    DefaultCaret caret = (DefaultCaret) log.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    //        create the progress bar
    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(progressBar.getMinimum());
    progressBar.setVisible(false);
    progressBar.setStringPainted(true);
    //Create the settings pane
    generationSettingLabel = new JLabel("Generate:");
    SpinnerModel collusionsSpinnerModel = new SpinnerNumberModel(1, 0, 3, 1);
    collusionSettingsPanel = new JPanel(new FlowLayout()) {
        @Override
        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    // collusionSettingsPanel.setLayout(new BoxLayout(collusionSettingsPanel, BoxLayout.X_AXIS));
    collusionsButton = new JSpinner(collusionsSpinnerModel);
    collusionsLabel = new JLabel("collusion(s)");
    collusionSettingsPanel.add(collusionsButton);
    collusionSettingsPanel.add(collusionsLabel);

    rankingSettingLabel = new JLabel("Rank by:");
    lossButton = new JRadioButton("loss");
    lossButton.setToolTipText("Sort sub-ideal models based on loss for Target of Assessment (high -> low)");
    gainButton = new JRadioButton("gain");
    gainButton.setToolTipText(
            "Sort sub-ideal models based on gain of any actor except Target of Assessment (high -> low)");
    lossGainButton = new JRadioButton("loss + gain");
    lossGainButton.setToolTipText(
            "Sort sub-ideal models based on loss for Target of Assessment and, if equal, on gain of any actor except Target of Assessment");
    //gainLossButton = new JRadioButton("gain + loss");
    lossGainButton.setSelected(true);
    rankingGroup = new ButtonGroup();
    rankingGroup.add(lossButton);
    rankingGroup.add(gainButton);
    rankingGroup.add(lossGainButton);
    //rankingGroup.add(gainLossButton);
    groupingSettingLabel = new JLabel("Group by:");
    groupingButton = new JCheckBox("collusion");
    groupingButton.setToolTipText(
            "Groups sub-ideal models based on the pair of actors colluding before ranking them");
    groupingButton.setSelected(false);
    refreshButton = new JButton("Refresh");
    refreshButton.addActionListener(this);

    settingsPanel = new JPanel();
    settingsPanel.setLayout(new BoxLayout(settingsPanel, BoxLayout.PAGE_AXIS));
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(generationSettingLabel);
    collusionSettingsPanel.setAlignmentX(LEFT_ALIGNMENT);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(collusionSettingsPanel);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    rankingSettingLabel.setAlignmentY(TOP_ALIGNMENT);
    settingsPanel.add(rankingSettingLabel);
    settingsPanel.add(lossButton);
    settingsPanel.add(gainButton);
    settingsPanel.add(lossGainButton);
    //settingsPanel.add(gainLossButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(groupingSettingLabel);
    settingsPanel.add(groupingButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
    settingsPanel.add(refreshButton);
    settingsPanel.add(Box.createRigidArea(new Dimension(0, 20)));
    progressBar.setPreferredSize(
            new Dimension(settingsPanel.getSize().width, progressBar.getPreferredSize().height));
    settingsPanel.add(progressBar);

    //Create the result tree
    root = new DefaultMutableTreeNode("No models to display");
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    //tree.setUI(new CustomTreeUI());
    tree.setCellRenderer(new CustomTreeCellRenderer(tree));
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setLargeModel(true);
    resultScrollPane = new JScrollPane(tree);
    tree.addTreeSelectionListener(treeSelectionListener);

    //tree.setShowsRootHandles(true);
    //Create a file chooser for saving
    sfc = new JFileChooser();
    FileFilter jpegFilter = new FileNameExtensionFilter("JPEG image", new String[] { "jpg", "jpeg" });
    sfc.addChoosableFileFilter(jpegFilter);
    sfc.setFileFilter(jpegFilter);

    //Create a file chooser for loading
    fc = new JFileChooser();
    FileFilter rdfFilter = new FileNameExtensionFilter("RDF file", "RDF");
    fc.addChoosableFileFilter(rdfFilter);
    fc.setFileFilter(rdfFilter);

    //Create the open button.  
    openButton = new JButton("Load model", createImageIcon("images/Open24.png"));
    openButton.addActionListener(this);
    openButton.setToolTipText("Load a e3value model");

    //Create the ideal graph button. 
    idealGraphButton = new JButton("Show ideal graph", createImageIcon("images/Plot.png"));
    idealGraphButton.setToolTipText("Display ideal profitability graph");
    idealGraphButton.addActionListener(this);

    Dimension thinButtonDimension = new Dimension(15, 420);

    //Create the expand subideal graph button. 
    expandButton = new JButton(">");
    expandButton.setPreferredSize(thinButtonDimension);
    expandButton.setMargin(new Insets(0, 0, 0, 0));
    expandButton.setToolTipText("Expand to show non-ideal profitability graph for selected model");
    expandButton.addActionListener(this);

    //Create the collapse sub-ideal graph button. 
    collapseButton = new JButton("<");
    collapseButton.setPreferredSize(thinButtonDimension);
    collapseButton.setMargin(new Insets(0, 0, 0, 0));
    collapseButton.setToolTipText("Collapse non-ideal profitability graph for selected model");
    collapseButton.addActionListener(this);

    //Create the generation button. 
    generateButton = new JButton("Generate sub-ideal models", createImageIcon("images/generate.png"));
    generateButton.addActionListener(this);
    generateButton.setToolTipText("Generate sub-ideal models for the e3value model currently loaded");

    //Create the chart panel
    chartPane = new JPanel();
    chartPane.setLayout(new FlowLayout(FlowLayout.LEFT));
    chartPane.add(expandButton);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
    buttonPanel.add(openButton);
    buttonPanel.add(Box.createRigidArea(new Dimension(20, 0)));
    buttonPanel.add(generateButton);
    buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
    buttonPanel.add(idealGraphButton);

    //Add the buttons, the ranking options, the result list and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(settingsPanel, BorderLayout.LINE_START);
    add(resultScrollPane, BorderLayout.CENTER);

    add(logScrollPane, BorderLayout.PAGE_END);
    add(chartPane, BorderLayout.LINE_END);
    //and make a nice border around it
    setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));
}

From source file:ch.randelshofer.cubetwister.PreferencesTemplatesPanel.java

private void chooseExternalTemplate(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseExternalTemplate
    if (importFileChooser == null) {
        importFileChooser = new JFileChooser();
        importFileChooser.setFileFilter(new ExtensionFileFilter("zip", "Zip Archive"));
        importFileChooser.setSelectedFile(
                new File(userPrefs.get("cubetwister.externalTemplate", "TinyLMS Template.zip")));
        importFileChooser.setApproveButtonText(labels.getString("filechooser.choose"));
    }//  w w  w  . j av a  2  s .c  o m
    if (JFileChooser.APPROVE_OPTION == importFileChooser.showOpenDialog(this)) {
        userPrefs.put("cubetwister.externalHTMLTemplate", importFileChooser.getSelectedFile().getPath());
        //externalTemplateField.setText(
        //      userPrefs.get("cubetwister.externalHTMLTemplate", ""));
    }
}

From source file:pt.lsts.neptus.console.plugins.AirOSPeers.java

public AirOSPeers(ConsoleLayout console) {
    super(console);
    setLayout(new BorderLayout());
    chart = ChartFactory.createTimeSeriesChart(null, "Time of day", "Link Quality", tsc, true, true, true);
    chart.getPlot().setBackgroundPaint(Color.black);
    cpanel = new ChartPanel(chart);
    add(cpanel, BorderLayout.CENTER);
    cpanel.getPopupMenu().add(I18n.text("Load Addresses")).addActionListener(new ActionListener() {
        @Override/*www  .  j  a  va 2s .co m*/
        public void actionPerformed(ActionEvent e) {
            try {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(GuiUtils.getCustomFileFilter("CSV Files", "csv"));
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int op = chooser.showOpenDialog(AirOSPeers.this);
                if (op == JFileChooser.APPROVE_OPTION)
                    WiFiMacAddresses.parseAddresses(new FileReader(chooser.getSelectedFile()));
            } catch (Exception ex) {
                GuiUtils.errorMessage(getConsole(), ex);
                ex.printStackTrace();
            }
        }
    });
    cpanel.getPopupMenu().addSeparator();
    cpanel.getPopupMenu().add(I18n.text("Clear")).addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tsc.removeAllSeries();
        }
    });
}