Example usage for javax.swing JOptionPane YES_NO_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_OPTION

Introduction

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

Prototype

int YES_NO_OPTION

To view the source code for javax.swing JOptionPane YES_NO_OPTION.

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.generic.GenericDoseResponseController.java

/**
 * Initialize main view//w w  w .ja v  a  2s . c  om
 */
@Override
protected void initMainView() {
    genericDRParentPanel = new GenericDRParentPanel();
    dRPanel = new DRPanel();
    //buttons disabled at start
    genericDRParentPanel.getCancelButton().setEnabled(false);
    genericDRParentPanel.getNextButton().setEnabled(false);
    getCardLayout().first(genericDRParentPanel.getContentPanel());
    onCardSwitch();
    //create a ButtonGroup for the radioButtons used for analysis
    ButtonGroup mainDRRadioButtonGroup = new ButtonGroup();
    //adding buttons to a ButtonGroup automatically deselect one when another one gets selected
    mainDRRadioButtonGroup.add(dRPanel.getInputDRButton());
    mainDRRadioButtonGroup.add(dRPanel.getInitialPlotDRButton());
    mainDRRadioButtonGroup.add(dRPanel.getNormalizedPlotDRButton());
    mainDRRadioButtonGroup.add(dRPanel.getResultsDRButton());
    //select as default first button
    dRPanel.getInputDRButton().setSelected(true);
    //init dataTable
    dataTable = new JTable();
    JScrollPane scrollPane = new JScrollPane(dataTable);
    //the table will take all the viewport height available
    dataTable.setFillsViewportHeight(true);
    scrollPane.getViewport().setBackground(Color.white);
    dataTable.getTableHeader().setReorderingAllowed(false);
    //row and column selection must be false
    //dataTable.setColumnSelectionAllowed(false);
    //dataTable.setRowSelectionAllowed(false);
    dRPanel.getDatatableDRPanel().add(scrollPane, BorderLayout.CENTER);
    setLogTransform(true);

    /**
     * Action listeners for uppermost panel.
     */
    //this button is ONLY used when going from the loading to the analysis
    genericDRParentPanel.getNextButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            genericDRParentPanel.getNextButton().setEnabled(false);
            genericDRParentPanel.getCancelButton().setEnabled(true);
            //save any metadata that was provided manually
            loadGenericDRDataController.setManualMetaData(importedDRDataHolder);
            //switch between child panels
            getCardLayout().next(genericDRParentPanel.getContentPanel());
            onCardSwitch();
        }
    });

    genericDRParentPanel.getCancelButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // warn the user and reset everything
            Object[] options = { "Yes", "No" };
            int showOptionDialog = JOptionPane.showOptionDialog(null,
                    "Current analysis won't be saved. Continue?", "", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[1]);
            if (showOptionDialog == 0) {
                // reset everything
                resetOnCancel();
            }
        }
    });

    /**
     * Action listeners for shared panel. When button is selected, switch
     * view to corresponding subview
     */
    dRPanel.getInputDRButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            //switch shared table view
            updateModelInTable(dRInputController.getTableModel());
            updateTableInfoMessage("This table contains all conditions and their respective responses");
            /**
             * for (int columnIndex = 0; columnIndex <
             * dataTable.getColumnCount(); columnIndex++) {
             * GuiUtils.packColumn(dataTable, columnIndex); }
             */
            dataTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.LEFT));
            //remove other panels
            dRInitialController.getInitialChartPanel().setChart(null);
            dRNormalizedController.getNormalizedChartPanel().setChart(null);
            dRResultsController.getDupeInitialChartPanel().setChart(null);
            dRResultsController.getDupeNormalizedChartPanel().setChart(null);
            dRPanel.getGraphicsDRParentPanel().removeAll();
            dRPanel.getGraphicsDRParentPanel().revalidate();
            dRPanel.getGraphicsDRParentPanel().repaint();
            //add panel to view
            dRPanel.getGraphicsDRParentPanel().add(dRInputController.getdRInputPanel(), gridBagConstraints);
        }
    });

    dRPanel.getInitialPlotDRButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (dRAnalysisGroup != null) {
                if (isFirstFitting()) {
                    initFirstFitting();
                    setFirstFitting(false);
                }
                //switch shared table view
                updateModelInTable(dRInitialController.getTableModel());
                updateTableInfoMessage(
                        "If you checked the box at the import screen, the doses have been log-transformed. Responses have not been changed");
                /**
                 * for (int columnIndex = 0; columnIndex <
                 * dataTable.getColumnCount(); columnIndex++) {
                 * GuiUtils.packColumn(dataTable, columnIndex); }
                 */
                dataTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.LEFT));
                //remove other panels
                dRNormalizedController.getNormalizedChartPanel().setChart(null);
                dRResultsController.getDupeInitialChartPanel().setChart(null);
                dRResultsController.getDupeNormalizedChartPanel().setChart(null);
                dRPanel.getGraphicsDRParentPanel().removeAll();
                dRPanel.getGraphicsDRParentPanel().revalidate();
                dRPanel.getGraphicsDRParentPanel().repaint();
                dRPanel.getGraphicsDRParentPanel().add(dRInitialController.getDRInitialPlotPanel(),
                        gridBagConstraints);
                //Plot fitted data in dose-response curve, along with R annotation
                plotDoseResponse(dRInitialController.getInitialChartPanel(),
                        dRInitialController.getDRInitialPlotPanel().getDoseResponseChartParentPanel(),
                        getDataToFit(false), getdRAnalysisGroup(), false);
            }
        }
    });

    dRPanel.getNormalizedPlotDRButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (dRAnalysisGroup != null) {
                //in case user skips "initial" subview and goes straight to normalization
                if (isFirstFitting()) {
                    initFirstFitting();
                    setFirstFitting(false);
                }
                //switch shared table view
                updateModelInTable(dRNormalizedController.getTableModel());
                updateTableInfoMessage(
                        "Potentially log-transformed doses with their normalized responses per replicate");
                /**
                 * for (int columnIndex = 0; columnIndex <
                 * dataTable.getColumnCount(); columnIndex++) {
                 * GuiUtils.packColumn(dataTable, columnIndex); }
                 */
                dataTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.LEFT));
                //remove other panels
                dRInitialController.getInitialChartPanel().setChart(null);
                dRResultsController.getDupeInitialChartPanel().setChart(null);
                dRResultsController.getDupeNormalizedChartPanel().setChart(null);
                dRPanel.getGraphicsDRParentPanel().removeAll();
                dRPanel.getGraphicsDRParentPanel().revalidate();
                dRPanel.getGraphicsDRParentPanel().repaint();
                dRPanel.getGraphicsDRParentPanel().add(dRNormalizedController.getDRNormalizedPlotPanel(),
                        gridBagConstraints);
                //Plot fitted data in dose-response curve, along with R annotation
                plotDoseResponse(dRNormalizedController.getNormalizedChartPanel(),
                        dRNormalizedController.getDRNormalizedPlotPanel().getDoseResponseChartParentPanel(),
                        getDataToFit(true), getdRAnalysisGroup(), true);
            }
        }
    });

    dRPanel.getResultsDRButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (dRAnalysisGroup != null) {
                //switch shared table view: create and set new table model with most recent statistical values
                // (these values get recalculated after each new fitting)
                dRResultsController.setTableModel(dRResultsController.reCreateTableModel(dRAnalysisGroup));
                updateModelInTable(dRResultsController.getTableModel());
                updateTableInfoMessage(
                        "Statistical values from the curve fit of the initial and normalized data.");

                //remove other panels
                dRInitialController.getInitialChartPanel().setChart(null);
                dRNormalizedController.getNormalizedChartPanel().setChart(null);
                dRPanel.getGraphicsDRParentPanel().removeAll();
                dRPanel.getGraphicsDRParentPanel().revalidate();
                dRPanel.getGraphicsDRParentPanel().repaint();
                dRPanel.getGraphicsDRParentPanel().add(dRResultsController.getdRResultsPanel(),
                        gridBagConstraints);
                //plot curves
                dRResultsController.plotCharts();
            }
        }
    });

    //add views to parent panels
    cellMissyController.getCellMissyFrame().getDoseResponseAnalysisParentPanel().add(genericDRParentPanel,
            gridBagConstraints);
    genericDRParentPanel.getDataLoadingPanel().add(loadGenericDRDataController.getDataLoadingPanel(),
            gridBagConstraints);
    genericDRParentPanel.getDoseResponseParentPanel().add(dRPanel, gridBagConstraints);
}

From source file:gdt.jgui.base.JPropertyPanel.java

/**
 * Response on menu action/*from www.java2 s.com*/
 * @param console main console
 * @param locator$ the locator string.
 */
@Override
public void response(JMainConsole console, String locator$) {
    try {
        //System.out.println("PropertyPanel:response:locator="+locator$);
        Properties locator = Locator.toProperties(locator$);
        String action$ = locator.getProperty(JRequester.REQUESTER_ACTION);
        String entihome$ = locator.getProperty(Entigrator.ENTIHOME);
        Entigrator entigrator = console.getEntigrator(entihome$);
        if (ACTION_ADD_PROPERTY.equals(action$)) {
            String text$ = locator.getProperty(JTextEditor.TEXT);
            //   System.out.println("PropertyPanel:response:property="+text$);
            if (text$ != null)
                entigrator.indx_addPropertyName(text$);
            JDesignPanel dp = new JDesignPanel();
            String dpLocator$ = dp.getLocator();
            dpLocator$ = Locator.append(dpLocator$, Entigrator.ENTIHOME, entihome$);
            dpLocator$ = Locator.append(dpLocator$, JDesignPanel.PROPERTY_NAME, text$);
            JConsoleHandler.execute(console, dpLocator$);
            return;
        }
        if (ACTION_EDIT_PROPERTY.equals(action$)) {
            String text$ = locator.getProperty(JTextEditor.TEXT);
            String propertyName$ = locator.getProperty(JDesignPanel.PROPERTY_NAME);
            //   System.out.println("PropertyPanel:response:set  property name ="+propertyName$+" new="+text$);
            if (text$ != null)
                entigrator.prp_editPropertyName(propertyName$, text$);

            JDesignPanel dp = new JDesignPanel();
            String dpLocator$ = dp.getLocator();
            dpLocator$ = Locator.append(dpLocator$, Entigrator.ENTIHOME, entihome$);
            dpLocator$ = Locator.append(dpLocator$, JDesignPanel.PROPERTY_NAME, text$);
            JConsoleHandler.execute(console, dpLocator$);
            return;
        }
        if (ACTION_CLEAR_PROPERTIES.equals(action$)) {
            //System.out.println("PropertyPanel:response:action="+action$);
            int response = JOptionPane.showConfirmDialog(console.getContentPanel(),
                    "Delete unused properties ?", "Confirm", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                entigrator.prp_deleteWrongEntries();
                JDesignPanel dp = new JDesignPanel();
                String dpLocator$ = dp.getLocator();
                dpLocator$ = Locator.append(dpLocator$, Entigrator.ENTIHOME, entihome$);
                JConsoleHandler.execute(console, dpLocator$);
                return;
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
    }
}

From source file:net.sf.jabref.util.Util.java

/**
 * Warns the user of undesired side effects of an explicit assignment/removal of entries to/from this group.
 * Currently there are four types of groups: AllEntriesGroup, SearchGroup - do not support explicit assignment.
 * ExplicitGroup - never modifies entries. KeywordGroup - only this modifies entries upon assignment/removal.
 * Modifications are acceptable unless they affect a standard field (such as "author") besides the "keywords" field.
 *
 * @param parent The Component used as a parent when displaying a confirmation dialog.
 * @return true if the assignment has no undesired side effects, or the user chose to perform it anyway. false
 * otherwise (this indicates that the user has aborted the assignment).
 */// w  w  w.j  a v a 2  s .  c o  m
public static boolean warnAssignmentSideEffects(List<AbstractGroup> groups, Component parent) {
    List<String> affectedFields = new ArrayList<>();
    for (AbstractGroup group : groups) {
        if (group instanceof KeywordGroup) {
            KeywordGroup kg = (KeywordGroup) group;
            String field = kg.getSearchField().toLowerCase();
            if ("keywords".equals(field)) {
                continue; // this is not undesired
            }
            int len = InternalBibtexFields.numberOfPublicFields();
            for (int i = 0; i < len; ++i) {
                if (field.equals(InternalBibtexFields.getFieldName(i))) {
                    affectedFields.add(field);
                    break;
                }
            }
        }
    }
    if (affectedFields.isEmpty()) {
        return true; // no side effects
    }

    // show a warning, then return
    StringBuilder message = new StringBuilder(
            Localization.lang("This action will modify the following field(s) in at least one entry each:"))
                    .append('\n');
    for (String affectedField : affectedFields) {
        message.append(affectedField).append('\n');
    }
    message.append(Localization.lang("This could cause undesired changes to your entries.")).append('\n')
            .append("It is recommended that you change the grouping field in your group definition to \"keywords\" or a non-standard name.")
            .append("\n\n").append(Localization.lang("Do you still want to continue?"));
    int choice = JOptionPane.showConfirmDialog(parent, message, Localization.lang("Warning"),
            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    return choice != JOptionPane.NO_OPTION;

    // if (groups instanceof KeywordGroup) {
    // KeywordGroup kg = (KeywordGroup) groups;
    // String field = kg.getSearchField().toLowerCase();
    // if (field.equals("keywords"))
    // return true; // this is not undesired
    // for (int i = 0; i < GUIGlobals.ALL_FIELDS.length; ++i) {
    // if (field.equals(GUIGlobals.ALL_FIELDS[i])) {
    // // show a warning, then return
    // String message = Globals ...
    // .lang(
    // "This action will modify the \"%0\" field "
    // + "of your entries.\nThis could cause undesired changes to "
    // + "your entries, so it is\nrecommended that you change the grouping
    // field "
    // + "in your group\ndefinition to \"keywords\" or a non-standard name."
    // + "\n\nDo you still want to continue?",
    // field);
    // int choice = JOptionPane.showConfirmDialog(parent, message,
    // Globals.lang("Warning"), JOptionPane.YES_NO_OPTION,
    // JOptionPane.WARNING_MESSAGE);
    // return choice != JOptionPane.NO_OPTION;
    // }
    // }
    // }
    // return true; // found no side effects
}

From source file:com.biosis.sgb.vistas.dialogos.PersonaCRUD.java

private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
    // TODO add your handling code here:
    this.accion = ELIMINAR;
    if (JOptionPane.showConfirmDialog(this, "Est seguro que desea eliminar esta persona?",
            "Mensaje del sistema", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
        if (this.personaControlador.accion(accion)) {
            FormularioUtil.mensajeExito(this, accion);
            this.persona = null;
            this.dispose();
        }//w  w  w . j  av a  2  s . co  m
    }
}

From source file:com.firmansyah.imam.sewa.kendaraan.FormUser.java

private void btnKeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKeluarActionPerformed
    int dialogButton = JOptionPane.YES_NO_OPTION;
    int dialogResult;
    dialogResult = JOptionPane.showConfirmDialog(this, "Anda Yakin Ingin Keluar? ", "Konfirmasi", dialogButton);
    if (dialogResult == 0) {
        System.out.println("Quit");
        this.dispose();
    } else {//from ww w .  j av  a 2s.  com
        System.out.println("cancel");
    }
}

From source file:condorclient.MainFXMLController.java

@FXML

void deleteButtonFired(ActionEvent event) {
    int delNo = 0;

    int n = JOptionPane.showConfirmDialog(null, "??", "",
            JOptionPane.YES_NO_OPTION);
    if (n == JOptionPane.YES_OPTION) {

        URL url = null;/* w ww  .ja  v a  2 s  . c o m*/
        XMLHandler handler = new XMLHandler();
        String scheddStr = handler.getURL("schedd");
        try {
            url = new URL(scheddStr);
            // url = new URL("http://localhost:9628");
        } catch (MalformedURLException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
        Schedd schedd = null;

        try {
            schedd = new Schedd(url);
        } catch (ServiceException ex) {
            Logger.getLogger(CondorClient.class.getName()).log(Level.SEVERE, null, ex);
        }

        //ClassAdStructAttr[]
        ClassAd ad = null;//birdbath.ClassAd;
        ClassAdStructAttr[][] classAdArray = null;

        int cluster = 0;

        int job = 0;
        Transaction xact = schedd.createTransaction();
        try {
            xact.begin(30);

        } catch (RemoteException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        final List<?> selectedNodeList = new ArrayList<>(table.getSelectionModel().getSelectedItems());
        String taskStatus = "";
        for (Object o : selectedNodeList) {
            if (o instanceof ObservableDisplayedClassAd) {
                delNo = Integer.parseInt(((ObservableDisplayedClassAd) o).getClusterId());
                taskStatus = ((ObservableDisplayedClassAd) o).getJobStatus();
                if (taskStatus.equals("")) {
                    JOptionPane.showMessageDialog(null, "?");
                    return;
                }
                String findreq = "owner==\"" + condoruser + "\"&&ClusterId==" + delNo;
                try {
                    classAdArray = schedd.getJobAds(findreq);
                } catch (RemoteException ex) {
                    Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
                }
                for (ClassAdStructAttr[] x : classAdArray) {
                    ad = new ClassAd(x);
                    job = Integer.parseInt(ad.get("ProcId"));
                    try {
                        xact.closeSpool(delNo, job);

                        // System.out.print("ts.getClusterId():" + showClusterId + "\n");
                    } catch (RemoteException ex) {
                        Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                try {
                    xact.removeCluster(delNo, "");
                } catch (RemoteException ex) {
                    Logger.getLogger(MainFXMLController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //end

        try {
            xact.commit();
        } catch (RemoteException e) {

            e.printStackTrace();
        }
        //??
        //            XMLHandler handler = new XMLHandler();
        int delNo1[] = new int[1];//
        delNo1[0] = delNo;
        handler.removeJobs(delNo1, 1);

    } else if (n == JOptionPane.NO_OPTION) {
        System.out.println("qu xiao");

    }

}

From source file:gdt.jgui.entity.query.JQueryPanel.java

/**
 * Get the context menu.//from   w  w  w .ja  v a 2  s  .co  m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {
    menu = new JMenu("Context");
    menu.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            menu.removeAll();
            //            System.out.println("BookmarksEditor:getConextMenu:menu selected");
            JMenuItem selectItem = new JMenuItem("Select");
            selectItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    showHeader();
                    showContent();
                }
            });
            menu.add(selectItem);
            JMenuItem clearHeader = new JMenuItem("Clear all");
            clearHeader.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    clearHeader();
                    showHeader();
                    showContent();
                }
            });
            menu.add(clearHeader);
            Entigrator entigrator = console.getEntigrator(entihome$);
            Sack query = entigrator.getEntityAtKey(entityKey$);
            if (query.getElementItem("parameter", "noreset") == null) {
                JMenuItem resetItem = new JMenuItem("Reset");
                resetItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(),
                                "Reset source to default ?", "Confirm", JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION)
                            reset();
                    }
                });
                menu.add(resetItem);
            }
            JMenuItem folderItem = new JMenuItem("Open folder");
            folderItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        File file = new File(entihome$ + "/" + entityKey$);
                        Desktop.getDesktop().open(file);
                    } catch (Exception ee) {
                        Logger.getLogger(getClass().getName()).info(ee.toString());
                    }
                }
            });
            menu.add(folderItem);

            menu.addSeparator();
            JMenuItem addHeader = new JMenuItem("Add column");
            addHeader.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    addHeader();
                }
            });
            menu.add(addHeader);
            JMenuItem removeColumn = new JMenuItem("Remove column ");
            removeColumn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    removeColumn();
                }
            });
            menu.add(removeColumn);
            ListSelectionModel lsm = table.getSelectionModel();
            if (!lsm.isSelectionEmpty()) {
                JMenuItem excludeRows = new JMenuItem("Exclude rows ");
                excludeRows.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Entigrator entigrator = console.getEntigrator(entihome$);
                        Sack query = entigrator.getEntityAtKey(entityKey$);
                        if (!query.existsElement("exclude"))
                            query.createElement("exclude");
                        //else
                        //   query.clearElement("exclude");
                        ListSelectionModel lsm = table.getSelectionModel();
                        int minIndex = lsm.getMinSelectionIndex();
                        int maxIndex = lsm.getMaxSelectionIndex();
                        for (int i = minIndex; i <= maxIndex; i++) {
                            if (lsm.isSelectedIndex(i)) {
                                System.out.println("JQueryPanel:exclude rows:label=" + table.getValueAt(i, 1));
                                query.putElementItem("exclude",
                                        new Core(null, (String) table.getValueAt(i, 1), null));
                            }
                        }
                        entigrator.save(query);
                        showHeader();
                        showContent();
                    }
                });
                menu.add(excludeRows);
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    return menu;
}

From source file:charitypledge.Pledge.java

private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {
    JFrame frame = new JFrame();
    int confirm = JOptionPane.showOptionDialog(frame, "Are You Sure to Close this Application?",
            "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
    if (confirm == JOptionPane.YES_OPTION) {
        System.exit(0);/*ww  w .j  ava 2 s .  c  o m*/
    }
}

From source file:marytts.tools.voiceimport.DatabaseImportMain.java

protected void closeGUI() {
    // This doesn't work because Java cannot close the X11 connection, see
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4420885
    int answer = JOptionPane.showOptionDialog(this,
            "Do you want to close this GUI?\n\n"
                    + "The components that are currently running will continue to run,\n"
                    + "but you will not be able to save settings or select/deselect\n" + "components to run.\n"
                    + "This may be useful when running this tool using 'nohup' on a server\n"
                    + "because it allows you to log off without stopping the process.",
            "Really close GUI?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
    if (answer == JOptionPane.YES_OPTION) {
        this.setVisible(false);
        this.dispose();
    }//from  ww  w  .  j  a  va 2s .  c  o  m
}

From source file:App.java

/**
 * Initialize the contents of the frame.
 *//*  w w w  .ja  v  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();
        }
    });
}