Example usage for javax.swing JDialog setVisible

List of usage examples for javax.swing JDialog setVisible

Introduction

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

Prototype

public void setVisible(boolean b) 

Source Link

Document

Shows or hides this Dialog depending on the value of parameter b .

Usage

From source file:com.net2plan.gui.GUINet2Plan.java

private void showKeyCombinations() {
    Component component = container.getComponent(0);
    if (!(component instanceof IGUIModule)) {
        ErrorHandling.showErrorDialog("No tool is active", "Unable to show key associations");
        return;/* www.  j  a  v a2  s  .c o  m*/
    }

    final JDialog dialog = new JDialog();
    dialog.setTitle("Key combinations");
    SwingUtils.configureCloseDialogOnEscape(dialog);
    dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    dialog.setSize(new Dimension(500, 300));
    dialog.setLocationRelativeTo(null);
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    dialog.setLayout(new MigLayout("fill, insets 0 0 0 0"));

    final String[] tableHeader = StringUtils.arrayOf("Key combination", "Action");

    DefaultTableModel model = new ClassAwareTableModel();
    model.setDataVector(new Object[1][tableHeader.length], tableHeader);

    AdvancedJTable table = new AdvancedJTable(model);
    JScrollPane scrollPane = new JScrollPane(table);
    dialog.add(scrollPane, "grow");

    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);

    table.getTableHeader().addMouseListener(new ColumnFitAdapter());

    IGUIModule module = (IGUIModule) component;
    Map<String, KeyStroke> keyCombinations = module.getKeyCombinations();
    if (!keyCombinations.isEmpty()) {
        model.removeRow(0);

        for (Entry<String, KeyStroke> keyCombination : keyCombinations.entrySet()) {
            String description = keyCombination.getKey();
            KeyStroke keyStroke = keyCombination.getValue();
            model.addRow(StringUtils.arrayOf(description, keyStroke.toString().replaceAll(" pressed ", " ")));
        }
    }

    dialog.setVisible(true);
}

From source file:biomine.bmvis2.pipeline.sources.QueryGraphSource.java

@Override
public BMGraph getBMGraph() throws GraphOperationException {
    try {//from   w  w w  .  ja v a  2 s.c o  m
        if (fetch == null) {
            fetch = new CrawlerFetch(query, neighborhood, database);
        }
        if (ret == null) {
            final JDialog dial = new JDialog((JFrame) null);

            dial.setTitle("BMVIS II - Query to database");
            dial.setSize(400, 200);
            dial.setMinimumSize(new Dimension(400, 200));
            dial.setResizable(false);
            final JTextArea text = new JTextArea();
            text.setEditable(false);

            dial.add(text);
            text.setText("...");

            class Z {
                Exception runExc = null;
            }

            final Z z = new Z();
            Runnable fetchThread = new Runnable() {
                public void run() {
                    try {
                        long startTime = System.currentTimeMillis();
                        while (!fetch.isDone()) {
                            fetch.update();
                            Thread.sleep(500);
                            long time = System.currentTimeMillis();
                            long elapsed = time - startTime;

                            if (elapsed > 30000) {
                                throw new GraphOperationException("Timeout while querying " + query);
                            }
                            final String newText = fetch.getState() + ":\n" + fetch.getMessages();
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    text.setText(newText);
                                }
                            });
                        }

                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                dial.setVisible(false);
                            }
                        });

                    } catch (Exception e) {
                        z.runExc = e;
                    }

                }

            };

            new Thread(fetchThread).start();
            dial.setModalityType(ModalityType.APPLICATION_MODAL);
            dial.setVisible(true);
            ret = fetch.getBMGraph();
            if (ret == null)
                throw new GraphOperationException(fetch.getMessages());
            if (z.runExc != null) {
                if (z.runExc instanceof GraphOperationException)
                    throw (GraphOperationException) z.runExc;
                else
                    throw new GraphOperationException(z.runExc);
            }
        }

    } catch (IOException e) {
        throw new GraphOperationException(e);
    }
    updateInfo();
    return ret;
}

From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java

/**
 * Release resources right before throwing away this WindowManager instance.
 *//*from   ww w  . j  a  v a2  s  .c o  m*/
public void dispose() {
    for (WindowOpenInfo openInfo : windowOpenMode.values()) {
        if (openInfo.getOpenMode() == OpenMode.DIALOG) {
            JDialog dialog = (JDialog) openInfo.getData();
            dialog.setVisible(false);
        }
    }

    if (isMainWindowManager) {
        // Stop background tasks
        WatchDog watchDog = AppBeans.get(WatchDog.NAME);
        watchDog.stopTasks();
    }

    // Dispose windows
    for (Window window : windowOpenMode.keySet()) {
        Frame frame = window.getFrame();
        if (frame instanceof Component.Disposable)
            ((Component.Disposable) frame).dispose();
    }

    tabs.clear();
    windowOpenMode.clear();
    stacks.clear();
}

From source file:net.sf.jabref.openoffice.StyleSelectDialog.java

private void displayDefaultStyle(boolean authoryear) {
    try {/*from   w  w w .  ja va 2s  . c  o m*/
        // Read the contents of the default style file:
        URL defPath = authoryear ? JabRef.class.getResource(OpenOfficePanel.DEFAULT_AUTHORYEAR_STYLE_PATH)
                : JabRef.class.getResource(OpenOfficePanel.DEFAULT_NUMERICAL_STYLE_PATH);
        BufferedReader r = new BufferedReader(new InputStreamReader(defPath.openStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = r.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }

        // Make a dialog box to display the contents:
        final JDialog dd = new JDialog(diag, Localization.lang("Default style"), true);
        JLabel header = new JLabel(
                "<html>" + Localization.lang("The panel below shows the definition of the default style.")
                //+"<br>"
                        + Localization.lang(
                                "If you want to use it as a template for a new style, you can copy the contents into a new .jstyle file")
                        + "</html>");

        header.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        dd.getContentPane().add(header, BorderLayout.NORTH);
        JTextArea ta = new JTextArea(sb.toString());
        ta.setEditable(false);
        JScrollPane sp = new JScrollPane(ta);
        sp.setPreferredSize(new Dimension(700, 500));
        dd.getContentPane().add(sp, BorderLayout.CENTER);
        JButton okButton = new JButton(Localization.lang("OK"));
        ButtonBarBuilder bb = new ButtonBarBuilder();
        bb.addGlue();
        bb.addButton(okButton);
        bb.addGlue();
        bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        dd.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
        okButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                dd.dispose();
            }
        });
        dd.pack();
        dd.setLocationRelativeTo(diag);
        dd.setVisible(true);
    } catch (IOException ex) {
        LOGGER.warn("Problem showing default style", ex);
    }
}

From source file:ucar.unidata.idv.control.chart.ChartManager.java

/**
 * show dialog for chart//ww  w. j  a  v a 2 s. c  o m
 *
 * @param chartHolder chart
 */
protected void showPropertiesDialog(final ChartHolder chartHolder) {
    List comps = new ArrayList();
    getPropertiesComponents(chartHolder, comps);
    GuiUtils.tmpInsets = GuiUtils.INSETS_5;
    JComponent contents = GuiUtils.doLayout(comps, 2, GuiUtils.WT_NY, GuiUtils.WT_N);
    final JDialog propertiesDialog = GuiUtils.createDialog(chartHolder.getName() + " Properties", true);

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String cmd = ae.getActionCommand();
            if (cmd.equals(GuiUtils.CMD_OK) || cmd.equals(GuiUtils.CMD_APPLY)) {
                if (!applyProperties(chartHolder)) {
                    return;
                }
                updateThumb(true);
            }
            if (cmd.equals(GuiUtils.CMD_OK) || cmd.equals(GuiUtils.CMD_CANCEL)) {
                propertiesDialog.dispose();
            }
        }
    };
    JPanel buttons = GuiUtils.makeButtons(listener,
            new String[] { GuiUtils.CMD_APPLY, GuiUtils.CMD_OK, GuiUtils.CMD_CANCEL });

    contents = GuiUtils.centerBottom(contents, buttons);
    contents = GuiUtils.inset(contents, 5);
    propertiesDialog.getContentPane().add(GuiUtils.top(contents));
    propertiesDialog.pack();

    propertiesDialog.setLocation(200, 200);
    propertiesDialog.setVisible(true);
}

From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java

protected void closeWindow(Window window, WindowOpenInfo openInfo) {
    if (!disableSavingScreenHistory) {
        screenHistorySupport.saveScreenHistory(window, openInfo.getOpenMode());
    }// w ww.  j a  va2s  . c o m

    switch (openInfo.getOpenMode()) {
    case DIALOG: {
        JDialog dialog = (JDialog) openInfo.getData();
        dialog.setVisible(false);
        dialog.dispose();
        cleanupAfterModalDialogClosed(window);

        fireListeners(window, tabs.size() != 0);
        break;
    }
    case NEW_TAB:
    case NEW_WINDOW: {
        JComponent layout = (JComponent) openInfo.getData();
        layout.remove(DesktopComponentsHelper.getComposition(window));
        if (isMainWindowManager) {
            tabsPane.remove(layout);
        }

        WindowBreadCrumbs windowBreadCrumbs = tabs.get(layout);
        if (windowBreadCrumbs != null) {
            windowBreadCrumbs.clearListeners();
            windowBreadCrumbs.removeWindow();
        }

        tabs.remove(layout);
        stacks.remove(windowBreadCrumbs);

        fireListeners(window, tabs.size() != 0);
        if (!isMainWindowManager) {
            closeFrame(getFrame());
        }
        break;
    }
    case THIS_TAB: {
        JComponent layout = (JComponent) openInfo.getData();

        final WindowBreadCrumbs breadCrumbs = tabs.get(layout);
        if (breadCrumbs == null)
            throw new IllegalStateException("Unable to close screen: breadCrumbs not found");

        breadCrumbs.removeWindow();
        Window currentWindow = breadCrumbs.getCurrentWindow();
        if (!stacks.get(breadCrumbs).empty()) {
            Map.Entry<Window, Integer> entry = stacks.get(breadCrumbs).pop();
            putToWindowMap(entry.getKey(), entry.getValue());
        }
        JComponent component = DesktopComponentsHelper.getComposition(currentWindow);
        Window currentWindowFrame = (Window) currentWindow.getFrame();
        final java.awt.Component focusedCmp = windowOpenMode.get(currentWindowFrame).getFocusOwner();
        if (focusedCmp != null) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    focusedCmp.requestFocus();
                }
            });
        }
        layout.remove(DesktopComponentsHelper.getComposition(window));

        if (App.getInstance().getConnection().isConnected()) {
            layout.add(component);
            if (isMainWindowManager) {
                // If user clicked on close button maybe selectedIndex != tabsPane.getSelectedIndex()
                // Refs #1117
                int selectedIndex = 0;
                while ((selectedIndex < tabs.size()) && (tabsPane.getComponentAt(selectedIndex) != layout)) {
                    selectedIndex++;
                }
                if (selectedIndex == tabs.size()) {
                    selectedIndex = tabsPane.getSelectedIndex();
                }

                setActiveWindowCaption(currentWindow.getCaption(), currentWindow.getDescription(),
                        selectedIndex);
            } else {
                setTopLevelWindowCaption(currentWindow.getCaption());
                component.revalidate();
                component.repaint();
            }
        }

        fireListeners(window, tabs.size() != 0);
        break;
    }

    default:
        throw new UnsupportedOperationException();
    }
}

From source file:ProtocolRunner.java

void showDialog(JDialog dialog) {
    dialog.pack();
    dialog.setLocationRelativeTo(this);
    dialog.setVisible(true);
}

From source file:de.codesourcery.jasm16.ide.ui.utils.UIUtils.java

public static void showErrorDialog(Component parent, String title, String textMessage, Throwable cause) {
    final String stacktrace;
    if (cause == null) {
        stacktrace = null;/*from  w w w.ja v a  2  s.  com*/
    } else {
        final ByteArrayOutputStream stackTrace = new ByteArrayOutputStream();
        cause.printStackTrace(new PrintStream(stackTrace));
        stacktrace = new String(stackTrace.toByteArray());
    }

    final JDialog dialog = new JDialog((Window) null, title);

    dialog.setModal(true);

    final JTextArea message = createMultiLineLabel(textMessage);
    final DialogResult[] outcome = { DialogResult.CANCEL };

    final JButton okButton = new JButton("Ok");
    okButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            outcome[0] = DialogResult.YES;
            dialog.dispose();
        }
    });

    final JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(okButton);

    final JPanel messagePanel = new JPanel();
    messagePanel.setLayout(new GridBagLayout());

    GridBagConstraints cnstrs = constraints(0, 0, true, true, GridBagConstraints.BOTH);
    cnstrs.weightx = 1;
    cnstrs.weighty = 0.1;
    cnstrs.gridheight = 1;
    messagePanel.add(message, cnstrs);

    if (stacktrace != null) {
        final JTextArea createMultiLineLabel = new JTextArea(stacktrace);

        createMultiLineLabel.setBackground(null);
        createMultiLineLabel.setEditable(false);
        createMultiLineLabel.setBorder(null);
        createMultiLineLabel.setLineWrap(false);
        createMultiLineLabel.setWrapStyleWord(false);

        final JScrollPane pane = new JScrollPane(createMultiLineLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        cnstrs = constraints(0, 1, true, true, GridBagConstraints.BOTH);
        cnstrs.weightx = 1.0;
        cnstrs.weighty = 0.9;
        cnstrs.gridwidth = GridBagConstraints.REMAINDER;
        cnstrs.gridheight = GridBagConstraints.REMAINDER;
        messagePanel.add(pane, cnstrs);
    }

    final JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    cnstrs = constraints(0, 0, true, false, GridBagConstraints.BOTH);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.gridheight = 1;
    cnstrs.weighty = 1.0;
    cnstrs.insets = new Insets(5, 2, 5, 2); // top,left,bottom,right           
    panel.add(messagePanel, cnstrs);

    cnstrs = constraints(0, 1, true, true, GridBagConstraints.HORIZONTAL);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.gridheight = 1;
    cnstrs.weighty = 0;
    cnstrs.insets = new Insets(0, 2, 10, 2); // top,left,bottom,right      
    panel.add(buttonPanel, cnstrs);

    dialog.getContentPane().add(panel);

    dialog.setMinimumSize(new Dimension(600, 400));
    dialog.setPreferredSize(new Dimension(600, 400));
    dialog.setMaximumSize(new Dimension(600, 400));

    dialog.pack();
    dialog.setVisible(true);
}

From source file:org.fhcrc.cpl.viewer.amt.AmtDatabaseMatcher.java

/**
 * Separating this out so the interesting code flows better
 * @param matchingResult//from w ww  . jav a2s.  com
 */
public void createMassTimeErrorPlots(FeatureSetMatcher.FeatureMatchingResult matchingResult) {

    int numUnambiguousMatches = 0;
    for (Feature ms1Feature : matchingResult.getMasterSetFeatures()) {
        if (matchingResult.get(ms1Feature).size() == 1)
            numUnambiguousMatches++;
    }
    double[] ms1FeatureMasses = new double[numUnambiguousMatches];
    double[] ms1FeatureHydrophobicities = new double[numUnambiguousMatches];
    double[] massErrorData = new double[numUnambiguousMatches];
    double[] elutionErrorData = new double[numUnambiguousMatches];
    int i = 0;
    for (Feature ms1Feature : matchingResult.getMasterSetFeatures()) {
        ms1FeatureMasses[i] = ms1Feature.getMass();
        ms1FeatureHydrophobicities[i] = AmtExtraInfoDef.getObservedHydrophobicity(ms1Feature);

        if (matchingResult.get(ms1Feature).size() > 1)
            continue;

        Feature matchedAmtFeature = matchingResult.get(ms1Feature).get(0);
        //convert to ppm
        massErrorData[i] = (ms1Feature.getMass() - matchedAmtFeature.getMass())
                * (1000000 / ms1Feature.getMass());
        //System.err.println("Error: " + histogramData[i-1] + ", " +ms1Feature.getMass() + ", " + result.get(ms1Feature).get(0).getMass());

        elutionErrorData[i] = (AmtExtraInfoDef.getObservedHydrophobicity(ms1Feature)
                - (AmtExtraInfoDef.getObservedHydrophobicity(matchedAmtFeature)));
        i++;
    }

    //3D mass-elution histogram
    JDialog perspDialog = new JDialog();
    perspDialog.setSize(1000, 800);
    massTimeErrorPerspectivePlot = new PanelWithRPerspectivePlot();
    massTimeErrorPerspectivePlot.setChartHeight(800);
    massTimeErrorPerspectivePlot.setChartWidth(1000);

    massTimeErrorPerspectivePlot.setSize(1000, 800);
    massTimeErrorPerspectivePlot.setTiltAngle(25);
    massTimeErrorPerspectivePlot.setRotationAngle(-30);
    massTimeErrorPerspectivePlot.setAxisRVariableNames("Hydrophobicity", "Mass_ppm", "Matches");
    double xBinSize = .002;
    double yBinSize = 1;
    massTimeErrorPerspectivePlot.plotPointsSummary(elutionErrorData, massErrorData, xBinSize, yBinSize);
    perspDialog.add(massTimeErrorPerspectivePlot);
    perspDialog.setVisible(true);

    //scatterplot of mass vs. deltaMass
    ScatterPlotDialog spd = new ScatterPlotDialog(ms1FeatureMasses, massErrorData,
            "MS1 feature mass vs. (signed) match mass error");
    spd.setAxisLabels("MS1 Feature Mass", "PPM error (MS1 - AMT)");
    massDeltaMassScatterPlot = spd.getPanelWithScatterPlot().getChart();
    spd.setVisible(true);

    //scatterplot of hydrophobicity error vs. mass error
    ScatterPlotDialog spdHandM = new ScatterPlotDialog(elutionErrorData, massErrorData,
            "MS1 feature mass error vs. H error");
    spdHandM.setAxisLabels("H error", "PPM error");
    spdHandM.setVisible(true);
}

From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java

private void wireUp() {
    fileItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            if (actionEvent.getSource() == fileItem) {
                currentLocation = new File(retrieveFromDb.retrieveOpenLocation());
                fileChooser.setCurrentDirectory(currentLocation);
                int returnedVal = fileChooser.showOpenDialog(getParent());

                if (returnedVal == JFileChooser.APPROVE_OPTION) {
                    currentLocation = fileChooser.getCurrentDirectory();
                    retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                    RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
                    root.getGlassPane().setCursor(WAIT_CURSOR);
                    root.getGlassPane().setVisible(true);

                    File[] files = fileChooser.getSelectedFiles();
                    for (File file : files) {
                        if (file.isDirectory()) {
                            File[] fileArray = file.listFiles();
                            Arrays.sort(fileArray, new FileNameComparator());
                            for (File children : fileArray) {
                                if (isCorrect(children)) {
                                    xmlEadListModel.addFile(children);
                                }/*w  w  w.j a v  a  2s  . com*/
                            }
                        } else {
                            if (isCorrect(file)) {
                                xmlEadListModel.addFile(file);
                            }
                        }
                    }

                    root.getGlassPane().setCursor(DEFAULT_CURSOR);
                    root.getGlassPane().setVisible(false);
                }
            }
        }
    });
    repositoryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForRepositoryCode();
        }
    });
    countryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForCountryCode();
        }
    });
    checksLoadingFilesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            createOptionPaneForChecksLoadingFiles();
        }
    });
    createEag2012FromExistingEag2012.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eagFileChooser = new JFileChooser();
            eagFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eagFileChooser.setMultiSelectionEnabled(false);
            eagFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eagFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eagFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eagFile = eagFileChooser.getSelectedFile();
                if (!Eag2012Frame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eagFile, "eag")) {
                            new Eag2012Frame(eagFile, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });
    createEag2012FromScratch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!Eag2012Frame.isUsed()) {
                new Eag2012Frame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(),
                        labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode());
            }
        }
    });
    digitalObjectTypeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!DigitalObjectAndRightsOptionFrame.isInUse()) {
                JFrame DigitalObjectAndRightsOptionFrame = new DigitalObjectAndRightsOptionFrame(labels,
                        retrieveFromDb);

                DigitalObjectAndRightsOptionFrame.setPreferredSize(new Dimension(
                        getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 4));
                DigitalObjectAndRightsOptionFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                DigitalObjectAndRightsOptionFrame.pack();
                DigitalObjectAndRightsOptionFrame.setVisible(true);
            }
        }
    });
    defaultSaveFolderItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JFileChooser defaultSaveFolderChooser = new JFileChooser();
            defaultSaveFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            defaultSaveFolderChooser.setMultiSelectionEnabled(false);
            defaultSaveFolderChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveDefaultSaveFolder()));
            if (defaultSaveFolderChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File directory = defaultSaveFolderChooser.getSelectedFile();
                if (directory.canWrite() && DirectoryPermission.canWrite(directory)) {
                    retrieveFromDb.saveDefaultSaveFolder(directory + "/");
                } else {
                    createErrorOrWarningPanel(new Exception(labels.getString("error.directory.nowrites")),
                            false, labels.getString("error.directory.nowrites"), getContentPane());
                }
            }
        }
    });
    listDateConversionRulesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JDialog dateConversionRulesDialog = new DateConversionRulesDialog(labels, retrieveFromDb);

            dateConversionRulesDialog.setPreferredSize(
                    new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 7 / 8));
            dateConversionRulesDialog.setLocation(getContentPane().getWidth() / 8,
                    getContentPane().getHeight() / 8);

            dateConversionRulesDialog.pack();
            dateConversionRulesDialog.setVisible(true);

        }
    });
    edmGeneralOptionsItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!EdmGeneralOptionsFrame.isInUse()) {
                JFrame edmGeneralOptionsFrame = new EdmGeneralOptionsFrame(labels, retrieveFromDb);

                edmGeneralOptionsFrame.setPreferredSize(new Dimension(getContentPane().getWidth() * 3 / 8,
                        getContentPane().getHeight() * 3 / 8));
                edmGeneralOptionsFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                edmGeneralOptionsFrame.pack();
                edmGeneralOptionsFrame.setVisible(true);
            }
        }
    });
    closeSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            xmlEadListModel.removeFiles(xmlEadList.getSelectedValues());
        }
    });
    saveSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String defaultOutputDirectory = retrieveFromDb.retrieveDefaultSaveFolder();
            boolean isMultipleFiles = xmlEadList.getSelectedIndices().length > 1;

            RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
            root.getGlassPane().setCursor(WAIT_CURSOR);
            root.getGlassPane().setVisible(true);

            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                String filePrefix = fileInstance.getFileType().getFilePrefix();

                //todo: do we really need this?
                filename = filename.startsWith("temp_") ? filename.replace("temp_", "") : filename;

                filename = !filename.endsWith(".xml") ? filename + ".xml" : filename;

                if (!fileInstance.isValid()) {
                    filePrefix = "NOT_" + filePrefix;
                }

                if (fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) {
                    TreeTableModel treeTableModel = tree.getTreeTableModel();
                    Document document = (Document) treeTableModel.getRoot();
                    try {
                        File file2 = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        File filetemp = new File(Utilities.TEMP_DIR + "temp_" + filename);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer output = tf.newTransformer();
                        output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
                        output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

                        DOMSource domSource = new DOMSource(document.getFirstChild());
                        output.transform(domSource, new StreamResult(filetemp));
                        output.transform(domSource, new StreamResult(file2));

                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        fileInstance.setCurrentLocation(filetemp.getAbsolutePath());
                    } catch (Exception ex) {
                        createErrorOrWarningPanel(ex, true, labels.getString("errorSavingTreeXML"),
                                getContentPane());
                    }
                } else if (fileInstance.isConverted()) {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(new File(fileInstance.getCurrentLocation()), newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                } else {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(selectedFile, newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                }
            }

            root.getGlassPane().setCursor(DEFAULT_CURSOR);
            root.getGlassPane().setVisible(false);

            if (isMultipleFiles) {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("filesInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            } else {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("fileInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            }
            xmlEadList.updateUI();
        }
    });
    saveMessageReportItem.addActionListener(
            new MessageReportActionListener(retrieveFromDb, this, fileInstances, labels, this));
    sendFilesWebDAV.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    quitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    xsltItem.addActionListener(new XsltAdderActionListener(this, labels));
    xsdItem.addActionListener(new XsdAdderActionListener(this, labels, retrieveFromDb));
    if (Utilities.isDev) {
        databaseItem.addActionListener(new DatabaseCheckerActionListener(retrieveFromDb, getContentPane()));
    }
    xmlEadList.addMouseListener(new ListMouseAdapter(xmlEadList, xmlEadListModel, deleteFileItem, this));
    xmlEadList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (xmlEadList.getSelectedValues() != null && xmlEadList.getSelectedValues().length != 0) {
                    if (xmlEadList.getSelectedValues().length > 1) {
                        //                            convertAndValidateBtn.setEnabled(true);
                        //                            validateSelectionBtn.setEnabled(true);
                        //                            if (isValidated(xmlEadList)) {
                        //                                convertEdmSelectionBtn.setEnabled(true);
                        //                            } else {
                        //                                convertEdmSelectionBtn.setEnabled(false);
                        //                            }
                        //                            disableAllBtnAndItems();
                        saveMessageReportItem.setEnabled(true);
                        changeInfoInGUI("");
                    } else {
                        //                            convertAndValidateBtn.setEnabled(false);
                        //                            validateSelectionBtn.setEnabled(false);
                        //                            convertEdmSelectionBtn.setEnabled(false);
                        changeInfoInGUI(((File) xmlEadList.getSelectedValue()).getName());
                        if (apePanel.getApeTabbedPane().getSelectedIndex() == APETabbedPane.TAB_EDITION) {
                            apePanel.getApeTabbedPane()
                                    .createEditionTree(((File) xmlEadList.getSelectedValue()));
                            if (tree != null) {
                                FileInstance fileInstance = fileInstances
                                        .get(((File) getXmlEadList().getSelectedValue()).getName());
                                tree.addMouseListener(new PopupMouseListener(tree, getDataPreparationToolGUI(),
                                        getContentPane(), fileInstance));
                            }
                        }
                        disableTabFlashing();
                    }
                    checkHoldingsGuideButton();
                } else {
                    //                        convertAndValidateBtn.setEnabled(false);
                    //                        validateSelectionBtn.setEnabled(false);
                    //                        convertEdmSelectionBtn.setEnabled(false);
                    createHGBtn.setEnabled(false);
                    analyzeControlaccessBtn.setEnabled(false);
                    changeInfoInGUI("");
                }
            }
        }

        private boolean isValidated(JList xmlEadList) {
            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                if (!fileInstance.isValid()) {
                    return false;
                }
            }
            return true;
        }
    });

    summaryWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_SUMMARY));
    validationWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_VALIDATION));
    conversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_CONVERSION));
    edmConversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDM));
    editionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDITION));

    internetApexItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            BareBonesBrowserLaunch.openURL("http://www.apex-project.eu/");
        }
    });

    /**
     * Option Edit apeEAC-CPF file in the menu
     */

    this.editEacCpfFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eacFileChooser = new JFileChooser();
            eacFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eacFileChooser.setMultiSelectionEnabled(false);
            eacFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eacFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eacFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eacFile = eacFileChooser.getSelectedFile();
                if (!EacCpfFrame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eacFile, "eac-cpf")) {
                            new EacCpfFrame(eacFile, true, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });

    /**
     * Option Create apeEAC-CPF in the menu
     */
    this.createEacCpf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!EacCpfFrame.isUsed()) {
                EacCpfFrame eacCpfFrame = new EacCpfFrame(getContentPane().getSize(),
                        (ProfileListModel) getXmlEadList().getModel(), labels,
                        retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode(), null,
                        null, null);
            }
        }
    });

}