Example usage for javax.swing JOptionPane showConfirmDialog

List of usage examples for javax.swing JOptionPane showConfirmDialog

Introduction

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

Prototype

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog where the number of choices is determined by the optionType parameter.

Usage

From source file:com.mindcognition.mindraider.ui.swing.trash.TrashJPanel.java

/**
 * Constructor.//from  w w  w .j  ava  2  s  .  co m
 */
private TrashJPanel() {
    treeNodeToResourceUriMap = new HashMap();

    rootNode = new DefaultMutableTreeNode(Messages.getString("TrashJPanel.notebookArchive"));
    treeModel = new DefaultTreeModel(rootNode);
    treeModel.addTreeModelListener(new MyTreeModelListener());

    tree = new JTree(treeModel);
    tree.setEditable(false);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeExpansionListener(this);
    tree.addTreeWillExpandListener(this);
    tree.setShowsRootHandles(true);
    tree.putClientProperty("JTree.lineStyle", "Angled");

    // tree rendered
    // TODO implement own renderer in order to tooltips
    tree.setCellRenderer(new TrashTreeCellRenderer(IconsRegistry.getImageIcon("trashFull.png"),
            IconsRegistry.getImageIcon("explorerNotebookIcon.png")));

    setLayout(new BorderLayout());

    // control panel
    JToolBar tp = new JToolBar();
    tp.setLayout(new GridLayout(1, 6));
    undoButton = new JButton("", IconsRegistry.getImageIcon("trashUndo.png"));
    undoButton.setEnabled(false);
    undoButton.setToolTipText("Restore Outline");
    undoButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            new RestoreNotebookJDialog((String) treeNodeToResourceUriMap.get(node), "Restore Outline",
                    "Restore", true);
        }
    });
    tp.add(undoButton);

    deleteButton = new JButton("", IconsRegistry.getImageIcon("explorerDeleteSmall.png"));
    deleteButton.setToolTipText("Delete Outline");
    deleteButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }

            int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
                    "Do you really want to DELETE this Outline?", "Delete Outline", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                MindRaider.labelCustodian.deleteOutline((String) treeNodeToResourceUriMap.get(node));
                refresh();
                ExplorerJPanel.getInstance().refresh();
            }
        }
    });
    tp.add(deleteButton);

    emptyButton = new JButton("", IconsRegistry.getImageIcon("trashEmpty.png"));

    emptyButton.setToolTipText(Messages.getString("TrashJPanel.emptyArchive"));
    emptyButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
                    "Do you really want to DELETE all discarded Outlines?", "Empty Trash",
                    JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                final SwingWorker worker = new SwingWorker() {

                    public Object construct() {
                        ProgressDialogJFrame progressDialogJFrame = new ProgressDialogJFrame("Empty Trash",
                                "<html><br>&nbsp;&nbsp;<b>Deleting:</b>&nbsp;&nbsp;</html>");
                        try {
                            ResourceDescriptor[] resourceDescriptors = MindRaider.labelCustodian
                                    .getDiscardedOutlineDescriptors();
                            if (resourceDescriptors != null) {
                                for (int i = 0; i < resourceDescriptors.length; i++) {
                                    MindRaider.labelCustodian.deleteOutline(resourceDescriptors[i].getUri());
                                }
                                refresh();
                            }
                        } finally {
                            if (progressDialogJFrame != null) {
                                progressDialogJFrame.dispose();
                            }
                        }
                        return null;
                    }
                };
                worker.start();
            }
        }
    });
    tp.add(emptyButton);

    add(tp, BorderLayout.NORTH);

    // add the tree
    JScrollPane scrollPane = new JScrollPane(tree);
    add(scrollPane);
    // build the whole tree
    buildTree();
    // click handler
    tree.addTreeSelectionListener(new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            logger.debug("Tree selection path: " + node.getPath()[node.getLevel()]);

            enableDisableToolbarButtons(node.getLevel());
        }
    });
}

From source file:components.DialogDemo.java

/** Creates the panel shown by the first tab. */
private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;/*from  ww  w.ja va 2  s  .  co  m*/

    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";

    radioButtons[0] = new JRadioButton("OK (in the L&F's words)");
    radioButtons[0].setActionCommand(defaultMessageCommand);

    radioButtons[1] = new JRadioButton("Yes/No (in the L&F's words)");
    radioButtons[1].setActionCommand(yesNoCommand);

    radioButtons[2] = new JRadioButton("Yes/No " + "(in the programmer's words)");
    radioButtons[2].setActionCommand(yeahNahCommand);

    radioButtons[3] = new JRadioButton("Yes/No/Cancel " + "(in the programmer's words)");
    radioButtons[3].setActionCommand(yncCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            //ok dialog
            if (command == defaultMessageCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.");

                //yes/no dialog
            } else if (command == yesNoCommand) {
                int n = JOptionPane.showConfirmDialog(frame, "Would you like green eggs and ham?",
                        "An Inane Question", JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Ewww!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Me neither!");
                } else {
                    setLabel("Come on -- tell me!");
                }

                //yes/no (not in those words)
            } else if (command == yeahNahCommand) {
                Object[] options = { "Yes, please", "No way!" };
                int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?",
                        "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("You're kidding!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("I don't like them, either.");
                } else {
                    setLabel("Come on -- 'fess up!");
                }

                //yes/no/cancel (not in those words)
            } else if (command == yncCommand) {
                Object[] options = { "Yes, please", "No, thanks", "No eggs, no ham!" };
                int n = JOptionPane.showOptionDialog(frame,
                        "Would you like some green eggs to go " + "with that ham?", "A Silly Question",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                        options[2]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Here you go: green eggs and ham!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("OK, just the ham, then.");
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    setLabel("Well, I'm certainly not going to eat them!");
                } else {
                    setLabel("Please tell me what you want!");
                }
            }
            return;
        }
    });

    return createPane(simpleDialogDesc + ":", radioButtons, showItButton);
}

From source file:com.emr.schemas.ButtonColumn.java

public void mouseClicked(MouseEvent e) {
    int row = table.getSelectedRow();
    int col = table.getSelectedColumn();

    if (col == 7) {
        //Ask user if they want to delete..
        int deleteProcess = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this process?",
                "Delete Process", JOptionPane.YES_NO_OPTION);
        if (deleteProcess == JOptionPane.YES_OPTION) {
            name = (String) table.getModel().getValueAt(row, 0);
            desc = (String) table.getModel().getValueAt(row, 1);
            new DeleteProcess().execute();

        }/*from  w  ww.j a  va2s . c o  m*/
    }
}

From source file:com._17od.upm.gui.DatabaseActions.java

/**
 * This method asks the user for the name of a new database and then creates
 * it. If the file already exists then the user is asked if they'd like to
 * overwrite it.//from  w ww.j  a  v  a  2  s  . c  om
 * @throws CryptoException 
 * @throws IOException 
 */
public void newDatabase() throws IOException, CryptoException {

    File newDatabaseFile = getSaveAsFile(Translator.translate("newPasswordDatabase"));
    if (newDatabaseFile == null) {
        return;
    }

    final JPasswordField masterPassword = new JPasswordField("");
    boolean passwordsMatch = false;
    do {

        //Get a new master password for this database from the user
        JPasswordField confirmedMasterPassword = new JPasswordField("");
        JOptionPane pane = new JOptionPane(
                new Object[] { Translator.translate("enterMasterPassword"), masterPassword,
                        Translator.translate("confirmation"), confirmedMasterPassword },
                JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        JDialog dialog = pane.createDialog(mainWindow, Translator.translate("masterPassword"));
        dialog.addWindowFocusListener(new WindowAdapter() {
            public void windowGainedFocus(WindowEvent e) {
                masterPassword.requestFocusInWindow();
            }
        });
        dialog.show();

        if (pane.getValue().equals(new Integer(JOptionPane.OK_OPTION))) {
            if (!Arrays.equals(masterPassword.getPassword(), confirmedMasterPassword.getPassword())) {
                JOptionPane.showMessageDialog(mainWindow, Translator.translate("passwordsDontMatch"));
            } else {
                passwordsMatch = true;
            }
        } else {
            return;
        }

    } while (passwordsMatch == false);

    if (newDatabaseFile.exists()) {
        newDatabaseFile.delete();
    }

    database = new PasswordDatabase(newDatabaseFile);
    dbPers = new PasswordDatabasePersistence(masterPassword.getPassword());
    saveDatabase();
    accountNames = new ArrayList();
    doOpenDatabaseActions();

    // If a "Database to Load on Startup" hasn't been set yet then ask the
    // user if they'd like to open this database on startup.
    if (Preferences.get(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP) == null
            || Preferences.get(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP).equals("")) {
        int option = JOptionPane.showConfirmDialog(mainWindow,
                Translator.translate("setNewLoadOnStartupDatabase"),
                Translator.translate("newPasswordDatabase"), JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION) {
            Preferences.set(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP,
                    newDatabaseFile.getAbsolutePath());
            Preferences.save();
        }
    }
}

From source file:com.emental.mindraider.ui.outline.OutlineArchiveJPanel.java

public void actionPerformed(ActionEvent e) {
    int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
            "Do you really want to restore this Note?", "Restore Note", JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION) {
        // determine selected concept parameters
        int selectedRow = table.getSelectedRow();
        if (selectedRow >= 0) {
            // map the row to the model (column sorters may change it)
            selectedRow = table.convertRowIndexToModel(selectedRow);

            if (tableModel.getDiscardedConcepts() != null
                    && tableModel.getDiscardedConcepts().length > selectedRow) {
                try {
                    MindRaider.noteCustodian.undiscard(MindRaider.profile.getActiveOutlineUri().toString(),
                            tableModel.getDiscardedConcepts()[selectedRow].getUri());
                } catch (Exception e1) {
                    logger.debug("Unable to restore the note!", e1); // {{debug}}
                }//from  w  ww  .j  a va 2 s.  com
                OutlineJPanel.getInstance().refresh();
            }
            return;
        }
    }
}

From source file:edu.ku.brc.af.ui.db.JEditComboBox.java

/**
 * It may or may not ask if it can add, and then it adds the new item
 * @param strArg the string that is to be added
 * @return whether it was added/* www. j  a v  a 2 s . co m*/
 */
protected boolean askToAdd(String strArg) {
    if (ignoreFocus) {
        return false;
    }

    if (isNotEmpty(strArg)) {
        ignoreFocus = true;

        String msg = UIRegistry.getLocalizedMessage("JEditComboBox.ADD_NEW_VALUE", strArg); //$NON-NLS-1$
        String title = UIRegistry.getResourceString("JEditComboBox.ADD_NEW_ITEM_TITLE"); //$NON-NLS-1$
        if (!askBeforeSave || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, title,
                JOptionPane.YES_NO_OPTION)) {
            PickListItemIFace pli = null;
            if (dbAdapter != null) {
                if (!dbAdapter.isReadOnly()) {
                    pli = dbAdapter.addItem(strArg, strArg);
                }
            } else {
                pli = new PickListItem(strArg, strArg, new Timestamp(System.currentTimeMillis())); // this is ok because the items will not be saved.
            }

            if (pli != null) {
                this.addItem(pli);
                this.setSelectedItem(pli);
            }

            ignoreFocus = false;

            return true;
        }
        ignoreFocus = false;
    }
    return false;
}

From source file:uk.co.petertribble.jkstat.gui.KstatBaseChartFrame.java

/**
 * Saves the current chart as an image in png format. The user can select
 * the filename, and is asked to confirm the overwrite of an existing file.
 *//*  ww w . j av a  2  s . co m*/
public void saveImage() {
    JFileChooser fc = new JFileChooser();
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        if (f.exists()) {
            int ok = JOptionPane.showConfirmDialog(this,
                    KstatResources.getString("SAVEAS.OVERWRITE.TEXT") + " " + f.toString(),
                    KstatResources.getString("SAVEAS.CONFIRM.TEXT"), JOptionPane.YES_NO_OPTION);
            if (ok != JOptionPane.YES_OPTION) {
                return;
            }
        }
        BufferedImage bi = kbc.getChart().createBufferedImage(500, 300);
        try {
            ImageIO.write(bi, "png", f);
            /*
             * According to the API docs this should throw an IOException
             * on error, but this doesn't seem to be the case. As a result
             * it's necessary to catch exceptions more generally. Even this
             * doesn't work properly, but at least we manage to convey the
             * message to the user that the write failed, even if the
             * error itself isn't handled.
             */
        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(this, ioe.toString(), KstatResources.getString("SAVEAS.ERROR.TEXT"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:DialogDemo.java

/** Creates the panel shown by the first tab. */
private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;// w  w  w . j av  a  2s.  c  o  m

    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";

    radioButtons[0] = new JRadioButton("OK (in the L&F's words)");
    radioButtons[0].setActionCommand(defaultMessageCommand);

    radioButtons[1] = new JRadioButton("Yes/No (in the L&F's words)");
    radioButtons[1].setActionCommand(yesNoCommand);

    radioButtons[2] = new JRadioButton("Yes/No " + "(in the programmer's words)");
    radioButtons[2].setActionCommand(yeahNahCommand);

    radioButtons[3] = new JRadioButton("Yes/No/Cancel " + "(in the programmer's words)");
    radioButtons[3].setActionCommand(yncCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // ok dialog
            if (command == defaultMessageCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.");

                // yes/no dialog
            } else if (command == yesNoCommand) {
                int n = JOptionPane.showConfirmDialog(frame, "Would you like green eggs and ham?",
                        "An Inane Question", JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Ewww!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Me neither!");
                } else {
                    setLabel("Come on -- tell me!");
                }

                // yes/no (not in those words)
            } else if (command == yeahNahCommand) {
                Object[] options = { "Yes, please", "No way!" };
                int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?",
                        "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("You're kidding!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("I don't like them, either.");
                } else {
                    setLabel("Come on -- 'fess up!");
                }

                // yes/no/cancel (not in those words)
            } else if (command == yncCommand) {
                Object[] options = { "Yes, please", "No, thanks", "No eggs, no ham!" };
                int n = JOptionPane.showOptionDialog(frame,
                        "Would you like some green eggs to go " + "with that ham?", "A Silly Question",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                        options[2]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Here you go: green eggs and ham!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("OK, just the ham, then.");
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    setLabel("Well, I'm certainly not going to eat them!");
                } else {
                    setLabel("Please tell me what you want!");
                }
            }
            return;
        }
    });

    return createPane(simpleDialogDesc + ":", radioButtons, showItButton);
}

From source file:dataviewer.DataViewer.java

/**
 * Creates new form DataViewer/*w  w  w. jav  a 2  s  . c  o  m*/
 */
public DataViewer() {
    try {
        for (Enum ee : THREAD.values()) {
            t[ee.ordinal()] = new Thread();
        }
        initComponents();
        DropTarget dropTarget = new DropTarget(tr_files, new DropTargetListenerImpl());
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                javax.swing.JTree tree = (javax.swing.JTree) e.getSource();
                TreePath path = tree.getSelectionPath();
                Object[] pnode = (Object[]) path.getPath();
                String name = pnode[pnode.length - 1].toString();
                String ex = getExtension(name);
                if (ex.equals(".txt") || ex.equals(".dat") || ex.equals(".csv") || ex.equals(".tsv")) {
                    selected_file = name;
                } else {
                    selected_file = "";
                }
            }
        };
        tr_files.addTreeSelectionListener(treeSelectionListener);

        tr_files.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >= 2) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                }
            }
        });

        tr_files.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    cur_path = (new File(cur_path)).getParent();
                    fill_tree();
                } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {

                    if (!"".equals(selected_file)) {
                        String name = cur_path + File.separator + selected_file;
                        if ((new File(name)).isFile()) {
                            int dialogResult = JOptionPane.showConfirmDialog(null,
                                    "Selected file [" + selected_file
                                            + "] will be removed and not recoverable.",
                                    "Are you sure?", JOptionPane.YES_NO_OPTION);
                            if (dialogResult == JOptionPane.YES_OPTION) {
                                (new File(name)).delete();
                                fill_tree();
                            }
                        }

                    } else {
                        JOptionPane.showMessageDialog(null,
                                "For safety concern, removing folder is not supported.", "Information",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        tr_files.setCellRenderer(new MyTreeCellRenderer());
        p_count.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

        //tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ctrl1, "tab_read");
        //tp_menu.getActionMap().put("tab_read", (Action) new ActionListenerImpl());
        //tp_menu.setMnemonicAt(0, KeyEvent.VK_1);
        //tp_menu.setMnemonicAt(1, KeyEvent.VK_2);
        /*InputMap inputMap = tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
         ActionMap actionMap = tp_menu.getActionMap();
                
         KeyStroke ctrl1 = KeyStroke.getKeyStroke("ctrl 1");
         inputMap.put(ctrl1, "tab_read");
         actionMap.put("tab_read", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(0);
         }
         });
                
         KeyStroke ctrl2 = KeyStroke.getKeyStroke("ctrl 2");
         inputMap.put(ctrl2, "tab_analyze");
         actionMap.put("tab_analyze", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(1);
         }
         });*/
        config();
    } catch (Exception e) {
        txt_count.setText(e.getMessage());
    }
}

From source file:edu.ucla.stat.SOCR.analyses.gui.PrincipalComponentAnalysis.java

/**This method defines the specific statistical Analysis to be carried our on the user specified data. ANOVA is done in this case. */
public void doAnalysis() {

    if (dataTable.isEditing())
        dataTable.getCellEditor().stopCellEditing();

    if (!hasExample) {
        JOptionPane.showMessageDialog(this, DATA_MISSING_MESSAGE);
        return;/*from  ww w  .  ja v  a  2s. c  o  m*/
    }

    Data data = new Data();

    String firstMessage = "Would you like to use all the data columns in this Principal Components Analysis?";
    String title = "SOCR - Principal Components Analysis";
    String secondMessage = "Please enter the column numbers (seperated by comma) that you would like to use.";
    String columnNumbers = "";

    int reply = JOptionPane.showConfirmDialog(null, firstMessage, title, JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION) {
        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        cellValue = null;
        int originalColumn = 0;

        for (int k = 0; k < dataTable.getColumnCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(0, k));

            if (cellValue != null && !cellValue.equals("")) {
                originalColumn++;

            }
        }

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, j) != null && !dataTable.getValueAt(k, j).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, j);
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues();

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }
        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }

        dependentHeader = "C1";
        independentHeader = "C2";
    }

    else { // start here
        try {
            columnNumbers = JOptionPane.showInputDialog(secondMessage);
        } catch (Exception e) {
        }

        String columnNumbersFinal = "," + columnNumbers.replaceAll("\\s", "") + ",";

        Vector<Integer> locationOfComma = new Vector<Integer>(100);

        for (int i = 0; i < columnNumbersFinal.length(); i++) {
            char d = columnNumbersFinal.charAt(i);
            if (d == ',')
                locationOfComma.add(i);
        }

        Vector<Integer> vector = new Vector<Integer>(100); // vector containing column selected numbers

        for (int i = 0; i < locationOfComma.size() - 1; i++) {
            String temp = columnNumbersFinal.substring(locationOfComma.get(i) + 1, locationOfComma.get(i + 1));
            if (temp == "")
                continue;
            vector.add((Integer.parseInt(temp) - 1));

        }

        dependentHeader = "C" + (vector.get(0) + 1);
        independentHeader = "C" + (vector.get(1) + 1);

        // System.out.println("Vector size is: " + vector.size() + "\n");                

        String cellValue = null;
        int originalRow = 0;

        for (int k = 0; k < dataTable.getRowCount(); k++) {
            cellValue = ((String) dataTable.getValueAt(k, 0));

            if (cellValue != null && !cellValue.equals("")) {
                originalRow++;

            }
        }

        int originalColumn = vector.size();

        dataRow = originalRow;
        dataColumn = originalColumn;

        String PCA_Data1[][] = new String[originalRow][originalColumn];
        double PCA_Data[][] = new double[originalRow][originalColumn];

        for (int k = 0; k < originalRow; k++)
            for (int j = 0; j < originalColumn; j++) {

                if (dataTable.getValueAt(k, vector.get(j)) != null
                        && !dataTable.getValueAt(k, vector.get(j)).equals("")) {
                    PCA_Data1[k][j] = (String) dataTable.getValueAt(k, vector.get(j));
                    PCA_Data[k][j] = Double.parseDouble(PCA_Data1[k][j]);
                }
            }

        double PCA_Adjusted_Data[][] = new double[originalRow][originalColumn];
        double column_Total = 0;
        double column_Mean = 0;

        for (int j = 0; j < originalColumn; j++)
            for (int k = 0; k < originalRow; k++) {
                column_Total += PCA_Data[k][j];

                if (k == (originalRow - 1)) {
                    column_Mean = column_Total / originalRow;

                    for (int p = 0; p < originalRow; p++) {
                        PCA_Adjusted_Data[p][j] = PCA_Data[p][j] - column_Mean;
                    }
                    column_Total = 0;
                    column_Mean = 0;
                }
            }

        Covariance cov = new Covariance(PCA_Adjusted_Data);
        RealMatrix matrix = cov.getCovarianceMatrix();

        EigenDecomposition eigenDecomp = new EigenDecomposition(matrix, 0);

        storedData = eigenDecomp;

        RealMatrix eigenvectorMatrix = eigenDecomp.getV();

        EValueArray = eigenDecomp.getRealEigenvalues(); // added              

        eigenvectorMatrix = eigenvectorMatrix.transpose();

        double eigenvectorArray[][] = eigenvectorMatrix.getData();

        /*for (int j = 0; j < 3; j++)
            for (int k = 0; k < 3; k++)
            {
                System.out.println(eigenvectorArray[j][k] + " ");
            } */

        Matrix matrix1 = new Matrix(eigenvectorArray);
        Matrix matrix2 = new Matrix(PCA_Adjusted_Data);
        matrix2 = matrix2.transpose();

        Matrix finalProduct = matrix1.times(matrix2);
        finalProduct = finalProduct.transpose();

        double finalArray[][] = finalProduct.getArrayCopy();

        /* for (int j = 0; j < dataTable.getColumnCount(); j++)
            for (int k = 0; k < dataTable.getRowCount(); k++)
            {
                System.out.println(finalArray[j][k] + " ");
            }*/

        for (int j = 0; j < originalRow; j++)
            for (int k = 0; k < originalColumn; k++) {
                PCATable.setValueAt(finalArray[j][k], j, k);
            }

        xData = new double[originalRow];
        yData = new double[originalRow];

        for (int i = 0; i < originalRow; i++) {
            xData[i] = finalArray[i][0];
        }

        for (int i = 0; i < originalRow; i++) {
            yData[i] = finalArray[i][1];
        }
    }

    map = new HashMap<Double, double[]>();

    for (int i = 0; i < dataColumn; i++) {
        map.put(EValueArray[i], storedData.getEigenvector(i).toArray());
    }

    Arrays.sort(EValueArray);

    xData1 = new double[EValueArray.length]; // for Scree Plot
    yData1 = new double[EValueArray.length];

    for (int i = 0; i < EValueArray.length; i++) {
        xData1[i] = i + 1;
    }

    for (int i = 0; i < EValueArray.length; i++) {
        yData1[i] = EValueArray[i];
    }

    for (int i = 0; i < yData1.length / 2; i++) {
        double temp = yData1[i];
        yData1[i] = yData1[yData1.length - i - 1];
        yData1[yData1.length - i - 1] = temp;
    }

    for (int i = 0; i < xData1.length; i++) {
        System.out.println("xData1 contains: " + xData1[i] + "\n");
    }

    for (int i = 0; i < yData1.length; i++) {
        System.out.println("yData1 contains: " + yData1[i] + "\n");
    }

    for (int i = 0; i < EValueArray.length / 2; i++) {
        double temp = EValueArray[i];
        EValueArray[i] = EValueArray[EValueArray.length - i - 1];
        EValueArray[EValueArray.length - i - 1] = temp;
    }

    resultPanelTextArea.append(
            "Click on \"PCA RESULT\" panel to view the transformed data (Eigenvector Transposed * Adjusted Data Transposed)");

    resultPanelTextArea.append("\n\nThe real eigenvalues (in descending order) are: \n\n");
    resultPanelTextArea.append("" + round(EValueArray[0], 3));

    for (int i = 1; i < EValueArray.length; i++) {
        resultPanelTextArea.append("\n" + round(EValueArray[i], 3));
    }
    resultPanelTextArea.append("\n\nThe corresponding eigenvectors (in columns) are: \n\n");

    double temp[] = new double[100];

    for (int j = 0; j < temp.length; j++)
        for (int i = 0; i < EValueArray.length; i++) {
            temp = map.get(EValueArray[i]);
            resultPanelTextArea.append("" + round(temp[j], 3) + "\t");
            if (i == EValueArray.length - 1) {
                resultPanelTextArea.append("\n");
            }
        }

    doGraph();
}