Example usage for javax.swing JDialog setLocationRelativeTo

List of usage examples for javax.swing JDialog setLocationRelativeTo

Introduction

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

Prototype

public void setLocationRelativeTo(Component c) 

Source Link

Document

Sets the location of the window relative to the specified component according to the following scenarios.

Usage

From source file:fxts.stations.util.preferences.EditAction.java

public void actionPerformed(ActionEvent aEvent) {
    JButton okButton = UIManager.getInst().createButton();
    JButton cancelButton = UIManager.getInst().createButton();
    final JDialog dialog = new JDialog(mEditorPanel.getParentDialog());
    dialog.setTitle(mEditorPanel.getTitle());
    JPanel editPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(UIFrontEnd.getInstance().getSideLayout());
    //mainPanel.setLayout(new SideLayout());

    //sets button panel
    buttonPanel.setLayout(UIFrontEnd.getInstance().getSideLayout());
    okButton.setText(mResMan.getString("IDS_OK_BUTTON"));
    //okButton.setPreferredSize(new Dimension(80, 27));
    GridBagConstraints sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    sideConstraints.insets = new Insets(10, 10, 10, 10);
    sideConstraints.gridx = 0;/*from ww  w  .ja v  a  2 s.  c  om*/
    sideConstraints.gridy = 0;
    ResizeParameterWrapper resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.5, 0.0, 0.5, 0.0);
    resizeParameter.setToConstraints(sideConstraints);
    buttonPanel.add(okButton, sideConstraints);
    cancelButton.setText(mResMan.getString("IDS_CANCEL_BUTTON"));
    //cancelButton.setPreferredSize(new Dimension(80, 27));
    sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    sideConstraints.insets = new Insets(10, 10, 10, 10);
    sideConstraints.gridx = 1;
    sideConstraints.gridy = 0;
    resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.5, 0.0, 0.5, 0.0);
    resizeParameter.setToConstraints(sideConstraints);
    buttonPanel.add(cancelButton, sideConstraints);

    //adds button panel
    sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    sideConstraints.insets = new Insets(10, 10, 10, 10);
    sideConstraints.gridx = 0;
    sideConstraints.gridy = 1;
    resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.0, 1.0, 1.0, 1.0);
    resizeParameter.setToConstraints(sideConstraints);
    mainPanel.add(buttonPanel, sideConstraints);

    //sets edit panel
    final IEditor editor = mType.getEditor();
    editor.setValue(mValue);
    editPanel.setLayout(UIFrontEnd.getInstance().getSideLayout());
    sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.0, 0.0, 1.0, 1.0);
    resizeParameter.setToConstraints(sideConstraints);
    Component editComp = editor.getComponent();

    //Mar 25 2004 - kav: added for right tab order at Font Chooser at java 1.4.
    if (editComp instanceof FontChooser) {
        FontChooser fc = (FontChooser) editComp;
        fc.setNextFocusedComp(okButton);
    }
    editPanel.add(editComp, sideConstraints);

    //adds editor panel
    sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    sideConstraints.gridx = 0;
    sideConstraints.gridy = 0;
    resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.0, 0.0, 1.0, 1.0);
    resizeParameter.setToConstraints(sideConstraints);
    mainPanel.add(editPanel, sideConstraints);

    //adds main panel
    dialog.getContentPane().setLayout(UIFrontEnd.getInstance().getSideLayout());
    //dialog.getContentPane().setLayout(new SideLayout());
    sideConstraints = UIFrontEnd.getInstance().getSideConstraints();
    sideConstraints.fill = GridBagConstraints.BOTH;
    resizeParameter = UIFrontEnd.getInstance().getResizeParameter();
    resizeParameter.init(0.0, 0.0, 1.0, 1.0);
    resizeParameter.setToConstraints(sideConstraints);
    dialog.getContentPane().add(mainPanel, sideConstraints);

    //adds listeners to buttons
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent aEvent) {
            if (editor.getValue().equals(mValue)) {
                //
            } else {
                mValue = editor.getValue();
                mEditorPanel.setValue(mValue);
                mEditorPanel.refreshControls();
                mEditorPanel.setValueChanged(true);
            }
            dialog.setVisible(false);
            dialog.dispose();
        }
    });
    okButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "ExitAction");
    okButton.getActionMap().put("ExitAction", new AbstractAction() {
        /**
         * Invoked when an action occurs.
         */
        public void actionPerformed(ActionEvent aEvent) {
            editor.setValue(mValue);
            dialog.setVisible(false);
            dialog.dispose();
        }
    });
    okButton.requestFocus();
    cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent aEvent) {
            editor.setValue(mValue);
            dialog.setVisible(false);
            dialog.dispose();
        }
    });
    //dialog.setResizable(false);
    dialog.setModal(true);
    dialog.pack();

    //sets minimal sizes for components
    Dimension dim = mainPanel.getSize();
    mainPanel.setMinimumSize(dim);
    mainPanel.setPreferredSize(dim);

    //sets size of buttons
    Dimension dimOkButton = okButton.getSize();
    Dimension dimCancelButton = cancelButton.getSize();
    int nMaxWidth = dimOkButton.getWidth() > dimCancelButton.getWidth() ? (int) dimOkButton.getWidth()
            : (int) dimCancelButton.getWidth();
    okButton.setPreferredSize(new Dimension(nMaxWidth, (int) dimOkButton.getHeight()));
    okButton.setSize(new Dimension(nMaxWidth, (int) dimOkButton.getHeight()));
    cancelButton.setPreferredSize(new Dimension(nMaxWidth, (int) dimCancelButton.getHeight()));
    cancelButton.setSize(new Dimension(nMaxWidth, (int) dimCancelButton.getHeight()));
    dialog.setLocationRelativeTo(dialog.getOwner());
    dialog.setVisible(true);
}

From source file:userinterface.graph.Histogram.java

/**
 * Generates the property dialog for a Histogram. Allows the user to select either a new or an exisitng Histogram
 * to plot data on/*  w  w  w  .  j a v a 2s .  com*/
 * 
 * @param defaultSeriesName
 * @param handler instance of {@link GUIGraphHandler}
 * @param minVal the min value in data cache
 * @param maxVal the max value in data cache
 * @return Either a new instance of a Histogram or an old one depending on what the user selects
 */

public static Pair<Histogram, SeriesKey> showPropertiesDialog(String defaultSeriesName, GUIGraphHandler handler,
        double minVal, double maxVal) {

    // make sure that the probabilities are valid
    if (maxVal > 1.0)
        maxVal = 1.0;
    if (minVal < 0.0)
        minVal = 0.0;

    // set properties for the dialog
    JDialog dialog = new JDialog(GUIPrism.getGUI(), "Histogram properties", true);
    dialog.setLayout(new BorderLayout());

    JPanel p1 = new JPanel(new FlowLayout());
    p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
            "Number of buckets"));

    JPanel p2 = new JPanel(new FlowLayout());
    p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
            "Series name"));

    JSpinner buckets = new JSpinner(new SpinnerNumberModel(10, 5, Integer.MAX_VALUE, 1));
    buckets.setToolTipText("Select the number of buckets for this Histogram");

    // provides the ability to select a new or an old histogram to plot the series on
    JTextField seriesName = new JTextField(defaultSeriesName);
    JRadioButton newSeries = new JRadioButton("New Histogram");
    JRadioButton existing = new JRadioButton("Existing Histogram");
    newSeries.setSelected(true);
    JPanel seriesSelectPanel = new JPanel();
    seriesSelectPanel.setLayout(new BoxLayout(seriesSelectPanel, BoxLayout.Y_AXIS));
    JPanel seriesTypeSelect = new JPanel(new FlowLayout());
    JPanel seriesOptionsPanel = new JPanel(new FlowLayout());
    seriesTypeSelect.add(newSeries);
    seriesTypeSelect.add(existing);
    JComboBox<String> seriesOptions = new JComboBox<>();
    seriesOptionsPanel.add(seriesOptions);
    seriesSelectPanel.add(seriesTypeSelect);
    seriesSelectPanel.add(seriesOptionsPanel);
    seriesSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Add series to"));

    // provides ability to select the min/max range of the plot
    JLabel minValsLabel = new JLabel("Min range:");
    JSpinner minVals = new JSpinner(new SpinnerNumberModel(0.0, 0.0, minVal, 0.01));
    minVals.setToolTipText("Does not allow value more than the min value in the probabilities");
    JLabel maxValsLabel = new JLabel("Max range:");
    JSpinner maxVals = new JSpinner(new SpinnerNumberModel(1.0, maxVal, 1.0, 0.01));
    maxVals.setToolTipText("Does not allow value less than the max value in the probabilities");
    JPanel minMaxPanel = new JPanel();
    minMaxPanel.setLayout(new BoxLayout(minMaxPanel, BoxLayout.X_AXIS));
    JPanel leftValsPanel = new JPanel(new BorderLayout());
    JPanel rightValsPanel = new JPanel(new BorderLayout());
    minMaxPanel.setBorder(
            BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Range"));
    leftValsPanel.add(minValsLabel, BorderLayout.WEST);
    leftValsPanel.add(minVals, BorderLayout.CENTER);
    rightValsPanel.add(maxValsLabel, BorderLayout.WEST);
    rightValsPanel.add(maxVals, BorderLayout.CENTER);
    minMaxPanel.add(leftValsPanel);
    minMaxPanel.add(rightValsPanel);

    // fill the old histograms in the property dialog

    boolean found = false;
    for (int i = 0; i < handler.getNumModels(); i++) {

        if (handler.getModel(i) instanceof Histogram) {

            seriesOptions.addItem(handler.getGraphName(i));
            found = true;
        }

    }

    existing.setEnabled(found);
    seriesOptions.setEnabled(false);

    // the bottom panel
    JPanel options = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton ok = new JButton("Plot");
    JButton cancel = new JButton("Cancel");

    // bind keyboard keys to plot and cancel buttons to improve usability

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        private static final long serialVersionUID = -7324877661936685228L;

        @Override
        public void actionPerformed(ActionEvent e) {

            ok.doClick();

        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "ok");
    cancel.getActionMap().put("ok", new AbstractAction() {

        private static final long serialVersionUID = 2642213543774356676L;

        @Override
        public void actionPerformed(ActionEvent e) {

            cancel.doClick();

        }
    });

    //Action listener for the new series radio button
    newSeries.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (newSeries.isSelected()) {

                existing.setSelected(false);
                seriesOptions.setEnabled(false);
                buckets.setEnabled(true);
                buckets.setToolTipText("Select the number of buckets for this Histogram");
                minVals.setEnabled(true);
                maxVals.setEnabled(true);
            }
        }
    });

    //Action listener for the existing series radio button
    existing.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existing.isSelected()) {

                newSeries.setSelected(false);
                seriesOptions.setEnabled(true);
                buckets.setEnabled(false);
                minVals.setEnabled(false);
                maxVals.setEnabled(false);
                buckets.setToolTipText("Number of buckets can't be changed on an existing Histogram");
            }

        }
    });

    //Action listener for the plot button
    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            dialog.dispose();

            if (newSeries.isSelected()) {

                hist = new Histogram();
                hist.setNumOfBuckets((int) buckets.getValue());
                hist.setIsNew(true);

            } else if (existing.isSelected()) {

                String HistName = (String) seriesOptions.getSelectedItem();
                hist = (Histogram) handler.getModel(HistName);
                hist.setIsNew(false);

            }

            key = hist.addSeries(seriesName.getText());

            if (minVals.isEnabled() && maxVals.isEnabled()) {

                hist.setMinProb((double) minVals.getValue());
                hist.setMaxProb((double) maxVals.getValue());

            }
        }
    });

    //Action listener for the cancel button
    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
            hist = null;
        }
    });

    dialog.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {

            hist = null;
        }
    });

    p1.add(buckets, BorderLayout.CENTER);

    p2.add(seriesName, BorderLayout.CENTER);

    options.add(ok);
    options.add(cancel);

    // add everything to the main panel of the dialog
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.add(seriesSelectPanel);
    mainPanel.add(p1);
    mainPanel.add(p2);
    mainPanel.add(minMaxPanel);

    // add main panel to the dialog
    dialog.add(mainPanel, BorderLayout.CENTER);
    dialog.add(options, BorderLayout.SOUTH);

    // set dialog properties
    dialog.setSize(320, 290);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setVisible(true);

    // return the user selected Histogram with the properties set
    return new Pair<Histogram, SeriesKey>(hist, key);
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error//from w ww . j  av a  2 s  .c om
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:ome.formats.importer.gui.FileQueueHandler.java

/**
 * Retrieve the file chooser's selected reader then iterate over
 * each of our supplied containers filtering out those whose format
 * do not match those of the selected reader.
 * /*w  w  w.  ja  v a  2 s  . co m*/
 * @param allContainers List of ImporterContainers
 */
private void handleFiles(List<ImportContainer> allContainers) {
    FileFilter selectedFilter = fileChooser.getFileFilter();
    IFormatReader selectedReader = null;

    if (selectedFilter instanceof FormatFileFilter) {
        log.debug("Selected file filter: " + selectedFilter);
        selectedReader = ((FormatFileFilter) selectedFilter).getReader();
    }

    List<ImportContainer> containers = new ArrayList<ImportContainer>();
    for (ImportContainer ic : allContainers) {
        if (selectedReader == null) {
            // The user selected "All supported file types"
            containers = allContainers;
            break;
        }
        String a = selectedReader.getFormat();
        String b = ic.getReader();
        if (a.equals(b) || b == null) {
            containers.add(ic);
        } else {
            log.debug(String.format("Skipping %s (%s != %s)", ic.getFile().getAbsoluteFile(), a, b));
        }
    }

    Boolean spw = spwOrNull(containers);

    if (containers.size() == 0 && !candidatesFormatException) {
        final JOptionPane optionPane = new JOptionPane("\nNo importable files found in this selection.",
                JOptionPane.WARNING_MESSAGE);
        final JDialog errorDialog = new JDialog(viewer, "No Importable Files Found", true);
        errorDialog.setContentPane(optionPane);

        optionPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                String prop = e.getPropertyName();

                if (errorDialog.isVisible() && (e.getSource() == optionPane)
                        && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                    errorDialog.dispose();
                }
            }
        });

        errorDialog.toFront();
        errorDialog.pack();
        errorDialog.setLocationRelativeTo(viewer);
        errorDialog.setVisible(true);
    }

    if (candidatesFormatException) {
        viewer.candidateErrorsCollected(viewer);
        candidatesFormatException = false;
    }

    if (spw == null) {
        addEnabled(true);
        containers.clear();
        return; // Invalid containers.
    }

    if (getOMEROMetadataStoreClient() != null && spw.booleanValue()) {
        addEnabled(true);
        SPWDialog dialog = new SPWDialog(config, viewer, "Screen Import", true, getOMEROMetadataStoreClient());
        if (dialog.cancelled == true || dialog.screen == null)
            return;
        for (ImportContainer ic : containers) {
            ic.setTarget(dialog.screen);
            String title = dialog.screen.getName().getValue();
            addFileToQueue(ic, title, false, 0);
        }

        qTable.centerOnRow(qTable.getQueue().getRowCount() - 1);
        qTable.importBtn.requestFocus();

    } else if (getOMEROMetadataStoreClient() != null) {
        addEnabled(true);
        ImportDialog dialog = new ImportDialog(config, viewer, "Image Import", true,
                getOMEROMetadataStoreClient());
        if (dialog.cancelled == true || dialog.dataset == null)
            return;

        Double[] pixelSizes = new Double[] { dialog.pixelSizeX, dialog.pixelSizeY, dialog.pixelSizeZ };
        Boolean useFullPath = config.useFullPath.get();
        if (dialog.useCustomNamingChkBox.isSelected() == false)
            useFullPath = null; //use the default bio-formats naming

        for (ImportContainer ic : containers) {
            ic.setTarget(dialog.dataset);
            ic.setUserPixels(pixelSizes);
            ic.setArchive(dialog.archiveImage.isSelected());
            String title = "";
            if (dialog.project.getId() != null) {
                ic.setProjectID(dialog.project.getId().getValue());
                title = dialog.project.getName().getValue() + " / " + dialog.dataset.getName().getValue();
            } else {
                title = "none / " + dialog.dataset.getName().getValue();
            }

            addFileToQueue(ic, title, useFullPath, config.numOfDirectories.get());
        }

        qTable.centerOnRow(qTable.getQueue().getRowCount() - 1);
        qTable.importBtn.requestFocus();
    } else {
        addEnabled(true);
        JOptionPane.showMessageDialog(viewer,
                "Due to an error the application is unable to \n"
                        + "retrieve an OMEROMetadataStore and cannot continue."
                        + "The most likely cause for this error is that you"
                        + "are not logged in. Please try to login again.");
    }
}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display errors in import dialog /*from   ww  w . j  a  va2s .  c o m*/
 * 
 * @param frame - parent frame
 */
private void importErrorsCollected(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nYour import has produced one or more errors, " + "\nvisit the 'Import Errors' tab for details.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog errorDialog = new JDialog(this, "Errors Collected", false);
    errorDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (errorDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                errorDialog.dispose();
            }
        }
    });

    errorDialog.toFront();
    errorDialog.pack();
    errorDialog.setLocationRelativeTo(frame);
    errorDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display errors in candidates dialog// w w w  .  j  a va2 s.  c om
 * 
 * @param frame - parent frame
 */
public void candidateErrorsCollected(Component frame) {
    errors_pending = false;
    final JOptionPane optionPane = new JOptionPane(
            "\nAdding these files to the queue has produced one or more errors and some"
                    + "\n files will not be displayed on the queue. View the 'Import Errors' tab for details.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog errorDialog = new JDialog(this, "Errors Collected", true);
    errorDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (errorDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                errorDialog.dispose();
            }
        }
    });

    errorDialog.toFront();
    errorDialog.pack();
    errorDialog.setLocationRelativeTo(frame);
    errorDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display failed sending errors dialog//from  w w  w . j  a v a2  s.c om
 * 
 * @param frame - parent frame
 */
public void sendingErrorsFailed(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nDue to an error we were not able to send your error messages."
                    + "\nto our feedback server. Please try again.",
            JOptionPane.WARNING_MESSAGE);

    final JDialog failedDialog = new JDialog(this, "Feedback Failed!", true);

    failedDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (failedDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                failedDialog.dispose();
            }
        }
    });

    failedDialog.toFront();
    failedDialog.pack();
    failedDialog.setLocationRelativeTo(frame);
    failedDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.ImportDialog.java

/**
 * Dialog explaining metadata limitations when changing the main dialog's naming settings
 * /*from   w w  w  .j av a 2s .c  om*/
 * @param frame - parent component
 */
public void sendNamingWarning(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nNOTE: Some file formats do not include the file name in their metadata, "
                    + "\nand disabling this option may result in files being imported without a "
                    + "\nreference to their file name. For example, 'myfile.lsm [image001]' "
                    + "\nwould show up as 'image001' with this optioned turned off.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog warningDialog = new JDialog(this, "Naming Warning!", true);
    warningDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (warningDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                warningDialog.dispose();
            }
        }
    });

    warningDialog.toFront();
    warningDialog.pack();
    warningDialog.setLocationRelativeTo(frame);
    warningDialog.setVisible(true);
}

From source file:org.apache.marmotta.splash.common.ui.MessageDialog.java

public static void show(String title, String message, String description) {
    final JDialog dialog = new JDialog((Frame) null, title);
    dialog.setModal(true);/*from   w ww. j a  va2s.  com*/
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final JPanel root = new JPanel(new GridBagLayout());
    root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    dialog.getRootPane().setContentPane(root);

    final JButton close = new JButton("OK");
    close.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.setVisible(false);
        }
    });
    GridBagConstraints cClose = new GridBagConstraints();
    cClose.gridx = 0;
    cClose.gridy = 2;
    cClose.gridwidth = 2;
    cClose.weightx = 1;
    cClose.weighty = 0;
    cClose.insets = new Insets(5, 5, 5, 5);

    root.add(close, cClose);
    dialog.getRootPane().setDefaultButton(close);

    Icon icon = loadIcon(MARMOTTA_ICON);
    if (icon != null) {
        JLabel lblIcn = new JLabel(icon);

        GridBagConstraints cIcon = new GridBagConstraints();
        cIcon.gridx = 1;
        cIcon.gridy = 0;
        cIcon.gridheight = 2;
        cIcon.fill = GridBagConstraints.NONE;
        cIcon.weightx = 0;
        cIcon.weighty = 1;
        cIcon.anchor = GridBagConstraints.NORTH;
        cIcon.insets = new Insets(10, 5, 5, 0);
        root.add(lblIcn, cIcon);
    }

    JLabel lblMsg = new JLabel("<html>" + StringEscapeUtils.escapeHtml3(message).replaceAll("\\n", "<br>"));
    lblMsg.setFont(lblMsg.getFont().deriveFont(Font.BOLD, 16f));
    GridBagConstraints cLabel = new GridBagConstraints();
    cLabel.gridx = 0;
    cLabel.gridy = 0;
    cLabel.fill = GridBagConstraints.BOTH;
    cLabel.weightx = 1;
    cLabel.weighty = 0.5;
    cLabel.insets = new Insets(5, 5, 5, 5);
    root.add(lblMsg, cLabel);

    JLabel lblDescr = new JLabel(
            "<html>" + StringEscapeUtils.escapeHtml3(description).replaceAll("\\n", "<br>"));
    cLabel.gridy++;
    cLabel.insets = new Insets(0, 5, 5, 5);
    root.add(lblDescr, cLabel);

    dialog.pack();
    dialog.setLocationRelativeTo(null);

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

From source file:org.apache.marmotta.splash.common.ui.SelectionDialog.java

public static int select(String title, String message, String description, List<Option> options,
        int defaultOption) {
    final JDialog dialog = new JDialog((Frame) null, title);
    dialog.setModal(true);//from   w ww. j  a va  2  s.c  o  m
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final AtomicInteger result = new AtomicInteger(Math.max(defaultOption, -1));

    JButton defaultBtn = null;

    final JPanel root = new JPanel(new GridBagLayout());
    root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    dialog.getRootPane().setContentPane(root);

    JLabel lblMsg = new JLabel("<html>" + StringEscapeUtils.escapeHtml3(message).replaceAll("\\n", "<br>"));
    lblMsg.setFont(lblMsg.getFont().deriveFont(Font.BOLD, 16f));
    GridBagConstraints cLabel = new GridBagConstraints();
    cLabel.gridx = 0;
    cLabel.gridy = 0;
    cLabel.fill = GridBagConstraints.BOTH;
    cLabel.weightx = 1;
    cLabel.weighty = 0.5;
    cLabel.insets = new Insets(5, 5, 5, 5);
    root.add(lblMsg, cLabel);

    JLabel lblDescr = new JLabel(
            "<html>" + StringEscapeUtils.escapeHtml3(description).replaceAll("\\n", "<br>"));
    cLabel.gridy++;
    cLabel.insets = new Insets(0, 5, 5, 5);
    root.add(lblDescr, cLabel);

    // All the options
    cLabel.ipadx = 10;
    cLabel.ipady = 10;
    cLabel.insets = new Insets(5, 15, 0, 15);
    for (int i = 0; i < options.size(); i++) {
        cLabel.gridy++;

        final Option o = options.get(i);
        final JButton btn = new JButton(
                "<html>" + StringEscapeUtils.escapeHtml3(o.label).replaceAll("\\n", "<br>"),
                MessageDialog.loadIcon(o.icon));
        if (StringUtils.isNotBlank(o.info)) {
            btn.setToolTipText("<html>" + StringEscapeUtils.escapeHtml3(o.info).replaceAll("\\n", "<br>"));
        }

        btn.setHorizontalAlignment(AbstractButton.LEADING);
        btn.setVerticalTextPosition(AbstractButton.CENTER);
        btn.setHorizontalTextPosition(AbstractButton.TRAILING);

        final int myAnswer = i;
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                result.set(myAnswer);
                dialog.setVisible(false);
            }
        });

        root.add(btn, cLabel);
        if (i == defaultOption) {
            dialog.getRootPane().setDefaultButton(btn);
            defaultBtn = btn;
        }
    }

    final Icon icon = MessageDialog.loadIcon();
    if (icon != null) {
        JLabel lblIcn = new JLabel(icon);

        GridBagConstraints cIcon = new GridBagConstraints();
        cIcon.gridx = 1;
        cIcon.gridy = 0;
        cIcon.gridheight = 2 + options.size();
        cIcon.fill = GridBagConstraints.NONE;
        cIcon.weightx = 0;
        cIcon.weighty = 1;
        cIcon.anchor = GridBagConstraints.NORTH;
        cIcon.insets = new Insets(10, 5, 5, 0);
        root.add(lblIcn, cIcon);
    }

    final JButton close = new JButton("Cancel");
    close.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result.set(-1);
            dialog.setVisible(false);
        }
    });
    GridBagConstraints cClose = new GridBagConstraints();
    cClose.gridx = 0;
    cClose.gridy = 2 + options.size();
    cClose.gridwidth = 2;
    cClose.weightx = 1;
    cClose.weighty = 0;
    cClose.insets = new Insets(15, 5, 5, 5);

    root.add(close, cClose);
    if (defaultOption < 0) {
        dialog.getRootPane().setDefaultButton(close);
        defaultBtn = close;
    }

    dialog.pack();
    dialog.setLocationRelativeTo(null);
    defaultBtn.requestFocusInWindow();

    dialog.setVisible(true);
    dialog.dispose();

    return result.get();
}