Example usage for javax.swing SwingUtilities getWindowAncestor

List of usage examples for javax.swing SwingUtilities getWindowAncestor

Introduction

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

Prototype

public static Window getWindowAncestor(Component c) 

Source Link

Document

Returns the first Window ancestor of c, or null if c is not contained inside a Window.

Usage

From source file:org.ut.biolab.medsavant.client.util.ClientMiscUtils.java

/**
 * Register the escape key so that it can be used to cancel the associated JDialog.
 *//*from   w  w w  .  j a  v  a2 s  . c o  m*/
public static void registerCancelButton(final JButton cancelButton) {
    KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    JDialog dialog = (JDialog) SwingUtilities.getWindowAncestor(cancelButton);
    dialog.getRootPane().registerKeyboardAction(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            cancelButton.doClick();
        }
    }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
}

From source file:org.wandora.application.gui.topicpanels.ProcessingTopicPanel.java

private void showRichErrorDialog(String msg) {
    final JTextArea area = new JTextArea();
    area.setFont(errorMessageFont);/*from  w  w w.j  a va 2 s  .  c  om*/
    //area.setPreferredSize(new Dimension(520, 180));
    area.setEditable(false);
    area.setText(msg);

    // Make the JOptionPane resizable using the HierarchyListener
    area.addHierarchyListener(new HierarchyListener() {
        public void hierarchyChanged(HierarchyEvent e) {
            Window window = SwingUtilities.getWindowAncestor(area);
            if (window instanceof Dialog) {
                Dialog dialog = (Dialog) window;
                if (!dialog.isResizable()) {
                    dialog.setResizable(true);
                }
            }
        }
    });

    JScrollPane scroller = new JScrollPane(area);
    scroller.setPreferredSize(new Dimension(520, 180));
    JOptionPane.showMessageDialog(Wandora.getWandora(), scroller, "Errors", JOptionPane.PLAIN_MESSAGE);
}

From source file:pcgen.gui2.tabs.SummaryInfoTab.java

@Override
public ModelMap createModels(final CharacterFacade character) {
    ModelMap models = new ModelMap();

    models.put(LabelAndFieldHandler.class, new LabelAndFieldHandler(character));
    models.put(ComboBoxRendererHandler.class, new ComboBoxRendererHandler(character));
    models.put(ComboBoxModelHandler.class, new ComboBoxModelHandler(character));

    models.put(RandomNameAction.class,
            new RandomNameAction(character, (JFrame) SwingUtilities.getWindowAncestor(this)));
    models.put(ClassLevelTableModel.class, new ClassLevelTableModel(character, classLevelTable, classComboBox));

    models.put(GenerateRollsAction.class, new GenerateRollsAction(character));
    models.put(RollMethodAction.class,
            new RollMethodAction(character, (JFrame) SwingUtilities.getWindowAncestor(this)));
    models.put(CreateMonsterAction.class,
            new CreateMonsterAction(character, (JFrame) SwingUtilities.getWindowAncestor(this)));
    models.put(AddLevelsAction.class, new AddLevelsAction(character));
    models.put(RemoveLevelsAction.class, new RemoveLevelsAction(character));
    models.put(StatTableModel.class, new StatTableModel(character, statsTable));
    models.put(LanguageTableModel.class, new LanguageTableModel(character, languageTable));
    models.put(InfoPaneHandler.class, new InfoPaneHandler(character, infoPane));
    models.put(ExpAddAction.class, new ExpAddAction(character));
    models.put(ExpSubtractAction.class, new ExpSubtractAction(character));
    models.put(TodoListHandler.class, new TodoListHandler(character));
    models.put(HPHandler.class, new HPHandler(character));
    return models;
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 * Uses a modal dialog in order to display the progress of the retrieval and
 * make the operation cancelable./*from w  w  w.  j  a  v  a  2s  .  c  om*/
 * @param documentFile
 * @return the retrieved images or {@code null} if the retrieval has been
 * canceled (in dialog)
 * @throws DocumentAddException
 * @throws InterruptedException
 * @throws ExecutionException
 */
/*
internal implementation notes:
- can't use ProgressMonitor without blocking EVT instead of a model dialog
when using SwingWorker.get
*/
public List<BufferedImage> retrieveImages(final File documentFile)
        throws DocumentAddException, InterruptedException, ExecutionException {
    if (documentFile == null) {
        throw new IllegalArgumentException("documentFile mustn't be null");
    }
    final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog(SwingUtilities.getWindowAncestor(this), //owner
            DocumentScanner.generateApplicationWindowTitle("Wait", APP_NAME, APP_VERSION), //dialogTitle
            "Retrieving image data", //labelText
            null //progressBarText
    );
    final SwingWorker<List<BufferedImage>, Void> worker = new SwingWorker<List<BufferedImage>, Void>() {
        @Override
        protected List<BufferedImage> doInBackground() throws Exception {
            List<BufferedImage> retValue = new LinkedList<>();
            try {
                InputStream pdfInputStream = new FileInputStream(documentFile);
                PDDocument document = PDDocument.load(pdfInputStream);
                @SuppressWarnings("unchecked")
                List<PDPage> pages = document.getDocumentCatalog().getAllPages();
                for (PDPage page : pages) {
                    if (dialog.isCanceled()) {
                        document.close();
                        MainPanel.LOGGER.debug("tab generation aborted");
                        return null;
                    }
                    BufferedImage image = page.convertToImage();
                    retValue.add(image);
                }
                document.close();
            } catch (IOException ex) {
                throw new DocumentAddException(ex);
            }
            return retValue;
        }

        @Override
        protected void done() {
        }
    };
    worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog));
    worker.execute();
    //the dialog will be visible until the SwingWorker is done
    dialog.setVisible(true);
    List<BufferedImage> retValue = worker.get();
    return retValue;
}

From source file:richtercloud.reflection.form.builder.components.AmountMoneyPanel.java

private void currencyManageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_currencyManageButtonActionPerformed
    AmountMoneyPanelManageDialog amountMoneyPanelManageDialog;
    try {//  w  w w. j  a v a2 s . co m
        amountMoneyPanelManageDialog = new AmountMoneyPanelManageDialog(amountMoneyCurrencyStorage,
                amountMoneyExchangeRateRetriever, messageHandler,
                (Frame) SwingUtilities.getWindowAncestor(this));
    } catch (AmountMoneyCurrencyStorageException ex) {
        this.messageHandler.handle(new Message(
                String.format("An exception occured during retrieval of currencies from the storage: %s",
                        ExceptionUtils.getRootCauseMessage(ex)),
                JOptionPane.ERROR_MESSAGE, "Exception occured"));
        return;
    }
    amountMoneyPanelManageDialog.pack();
    amountMoneyPanelManageDialog.setVisible(true);
    //handle manipulation result
    Currency selectedCurrency = (Currency) currencyComboBoxModel.getSelectedItem();
    //if currencyComboBoxModel is emptied item by item an item change event
    //is triggered for every removal which trigger conversion and thus
    //requires to fetch all exchange rates -> diff the model and the storage
    Set<Currency> storedCurrencies;
    try {
        storedCurrencies = amountMoneyCurrencyStorage.getCurrencies();
    } catch (AmountMoneyCurrencyStorageException ex) {
        throw new RuntimeException(ex);
    }
    for (Currency storedCurrency : storedCurrencies) {
        if (!comboBoxModelContains(currencyComboBoxModel, storedCurrency)) {
            currencyComboBoxModel.addElement(storedCurrency);
        }
    }
    for (int i = 0; i < currencyComboBoxModel.getSize(); i++) {
        Currency modelCurrency = currencyComboBoxModel.getElementAt(i);
        if (!storedCurrencies.contains(modelCurrency)) {
            currencyComboBoxModel.removeElement(modelCurrency);
        }
    }
    if (!storedCurrencies.contains(selectedCurrency)) {
        currencyComboBoxModel.setSelectedItem(currencyComboBoxModel.getElementAt(0));
    } else {
        currencyComboBoxModel.setSelectedItem(selectedCurrency);
    }
}

From source file:richtercloud.reflection.form.builder.components.AmountMoneyPanelManageDialog.java

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
    AmountMoneyPanelEditDialog amountMoneyPanelEditDialog;
    try {/* w w w. j a v  a2s  . com*/
        amountMoneyPanelEditDialog = new AmountMoneyPanelEditDialog(null, //currency (null indicates creation of a new currency)
                this.amountMoneyCurrencyStorage, this.amountMoneyExchangeRateRetriever, this.messageHandler,
                (Frame) SwingUtilities.getWindowAncestor(this) //parent
        );
    } catch (AmountMoneyCurrencyStorageException ex) {
        this.messageHandler.handle(new Message(
                String.format("An exception occured during retrieval of currencies from the storage: %s",
                        ExceptionUtils.getRootCauseMessage(ex)),
                JOptionPane.ERROR_MESSAGE, "Exception occured"));
        return;
    }
    amountMoneyPanelEditDialog.pack();
    amountMoneyPanelEditDialog.setVisible(true);
    Currency newCurrency = amountMoneyPanelEditDialog.getCurrency();
    try {
        this.amountMoneyCurrencyStorage.saveCurrency(newCurrency);
    } catch (AmountMoneyCurrencyStorageException ex) {
        this.messageHandler.handle(new Message(
                String.format("An exception occured during retrieval of currencies from the storage: %s",
                        ExceptionUtils.getRootCauseMessage(ex)),
                JOptionPane.ERROR_MESSAGE, "Exception occured"));
    }
    currencyListModel.add(0, newCurrency);
}

From source file:richtercloud.reflection.form.builder.components.AmountMoneyPanelManageDialog.java

private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
    Currency selectedCurrency = this.currencyList.getSelectedValue();
    AmountMoneyPanelEditDialog amountMoneyPanelEditDialog;
    try {//ww w.j a va2s. c  o  m
        amountMoneyPanelEditDialog = new AmountMoneyPanelEditDialog(selectedCurrency, //currency
                this.amountMoneyCurrencyStorage, this.amountMoneyExchangeRateRetriever, this.messageHandler,
                (Frame) SwingUtilities.getWindowAncestor(this) //parent
        );
    } catch (AmountMoneyCurrencyStorageException ex) {
        this.messageHandler.handle(new Message(
                String.format("An exception occured during retrieval of currencies from the storage: %s",
                        ExceptionUtils.getRootCauseMessage(ex)),
                JOptionPane.ERROR_MESSAGE, "Exception occured"));
        return;
    }
    amountMoneyPanelEditDialog.pack();
    amountMoneyPanelEditDialog.setVisible(true);
    Currency editedCurrency = amountMoneyPanelEditDialog.getCurrency();
    try {
        //since AmountMoneyCurrencyStorage doesn't keep track of the order of
        //currencies, simply remove and add the old and new instance
        this.amountMoneyCurrencyStorage.removeCurrency(selectedCurrency);
        this.amountMoneyCurrencyStorage.saveCurrency(editedCurrency);
    } catch (AmountMoneyCurrencyStorageException ex) {
        this.messageHandler.handle(new Message(
                String.format("An exception occured during retrieval of currencies from the storage: %s",
                        ExceptionUtils.getRootCauseMessage(ex)),
                JOptionPane.ERROR_MESSAGE, "Exception occured"));
    }
    int selectedCurrencyIndex = currencyListModel.indexOf(selectedCurrency);
    currencyListModel.remove(selectedCurrencyIndex);
    currencyListModel.add(selectedCurrencyIndex, editedCurrency);
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

private void parameterSelection(final int pos, final Object obj) {

    QueryParameter param = paramList.get(pos);
    parametersValues.put(param.getName(), obj);
    final Map<String, QueryParameter> dependents = ParameterManager.getInstance()
            .getChildDependentParameters(param);
    if (dependents.size() > 0) {

        Thread executorThread = new Thread(new Runnable() {

            public void run() {
                UIActivator activator = new UIActivator(
                        (JDialog) SwingUtilities.getWindowAncestor(RuntimeParametersPanel.this),
                        I18NSupport.getString("run.load.dependent.parameters"));
                activator.start();//from  w w w.j  av  a2 s .c o m

                try {
                    for (final QueryParameter qp : dependents.values()) {
                        Map<String, QueryParameter> map = ParameterManager.getInstance()
                                .getParentDependentParameters(qp);
                        Map<String, Object> vals = new HashMap<String, Object>();
                        boolean selected = true;
                        for (QueryParameter p : map.values()) {
                            Object v = parametersValues.get(p.getName());
                            if (((obj instanceof Object[]) && (((Object[]) obj).length == 0)) || (v == null)) {
                                selected = false;
                            }
                            vals.put(p.getName(), v);
                        }

                        final List<IdName> values = new ArrayList<IdName>();
                        // all parent parameters selected
                        if (selected) {
                            Query query = new Query(qp.getSource());
                            // no count and no check for other parameters completition
                            QueryExecutor executor = new QueryExecutor(query, map, vals, con, false, false,
                                    false);
                            executor.setTimeout(Globals.getQueryTimeout());
                            executor.setMaxRows(0);
                            QueryResult qr = executor.execute();
                            //int count = qr.getRowCount();
                            int columnCount = qr.getColumnCount();

                            // two columns in manual select source!!!
                            //for (int i = 0; i < count; i++) {
                            while (qr.hasNext()) {
                                IdName in = new IdName();
                                in.setId((Serializable) qr.nextValue(0));
                                if (columnCount == 1) {
                                    in.setName((Serializable) qr.nextValue(0));
                                } else {
                                    in.setName((Serializable) qr.nextValue(1));
                                }
                                values.add(in);
                            }
                            Collections.sort(values, new IdNameComparator(qp.getOrderBy()));
                            qr.close();
                        }
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                ArrayList<Serializable> defaultValues = qp.getDefaultValues();
                                if ((qp.getDefaultSourceValues() != null)
                                        && (qp.getDefaultSourceValues().size() > 1)) {
                                    defaultValues = qp.getDefaultSourceValues();
                                }
                                initParameterValue(getComponent(qp), values, qp.getName(), defaultValues);
                            }
                        });

                    }

                } catch (Exception ex) {
                    LOG.error(ex.getMessage(), ex);
                    ex.printStackTrace();
                } finally {
                    if (activator != null) {
                        activator.stop();
                    }
                }

            }
        }, "NEXT : " + getClass().getSimpleName());
        executorThread.setPriority(EngineProperties.getRunPriority());
        executorThread.start();
    }

}

From source file:ro.nextreports.designer.wizpublish.JcrBrowserTree.java

private boolean overwrite(String message) {
    Object[] options = { I18NSupport.getString("report.util.yes"), I18NSupport.getString("report.util.no") };
    int option = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(JcrBrowserTree.this), message,
            I18NSupport.getString("report.util.confirm"), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

    return (option == JOptionPane.YES_OPTION);
}

From source file:ro.nextreports.designer.wizpublish.PublishFileWizardPanel.java

private boolean selection(JcrBrowserTree jcrBrowserTree, byte type) {
    TreePath treePath = jcrBrowserTree.getSelectionPath();
    if (treePath == null) {
        return false;
    }/*from   w ww . j av  a 2  s  .  c om*/
    final DBBrowserNode selectedNode = (DBBrowserNode) treePath.getLastPathComponent();
    if ((type == DBObject.REPORTS_GROUP) || (type == DBObject.CHARTS_GROUP)) {
        boolean download = (Boolean) context.getAttribute(PublishWizard.DOWNLOAD);
        String path = selectedNode.getDBObject().getAbsolutePath();
        if (selectedNode.getDBObject().getType() == DBObject.FOLDER_REPORT) {
            pathTextField.setText(path);
            overwrite = false;
        } else if (selectedNode.getDBObject().getType() == DBObject.REPORTS_GROUP) {
            pathTextField.setText(JcrNodeExpander.REPORTS_ROOT);
            overwrite = false;
        } else if (selectedNode.getDBObject().getType() == DBObject.CHARTS_GROUP) {
            pathTextField.setText(JcrNodeExpander.CHARTS_ROOT);
            overwrite = false;
        } else if ((selectedNode.getDBObject().getType() == DBObject.REPORTS)
                || (selectedNode.getDBObject().getType() == DBObject.CHARTS)) {
            // report
            if (download) {
                pathTextField.setText(path);
            } else {
                pathTextField.setText(path.substring(0, path.lastIndexOf("/")));
                nameTextField.setText(path.substring(path.lastIndexOf("/") + 1));
            }
            overwrite = true;
        }

        if (download && !overwrite) {
            String entity = (String) context.getAttribute(WizardConstants.ENTITY);
            String name;
            if (WizardConstants.ENTITY_REPORT.equals(entity)) {
                name = I18NSupport.getString("report");
            } else {
                name = I18NSupport.getString("chart");
            }
            Show.info(SwingUtilities.getWindowAncestor(jcrBrowserTree),
                    I18NSupport.getString("download.name.select", name));
            return false;
        }

    } else if (type == DBObject.DATABASE) {
        if (selectedNode.getDBObject().getType() != DBObject.DATASOURCE) {
            return false;
        }
        dataSourceTextField.setText(selectedNode.getDBObject().getAbsolutePath());
    }
    return true;
}