Example usage for javax.swing JOptionPane showInputDialog

List of usage examples for javax.swing JOptionPane showInputDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Object showInputDialog(Component parentComponent, Object message, String title, int messageType,
        Icon icon, Object[] selectionValues, Object initialSelectionValue) throws HeadlessException 

Source Link

Document

Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified.

Usage

From source file:fi.elfcloud.client.tree.ClusterHierarchyModel.java

private String renameDataItem(String name) {
    name = (String) JOptionPane.showInputDialog(null,
            Messages.getString("ClusterHierarchyModel.dialog_rename_dataitem_text_1") + //$NON-NLS-1$
                    Messages.getString("ClusterHierarchyModel.dialog_rename_dataitem_text_2") + name, //$NON-NLS-1$
            Messages.getString("ClusterHierarchyModel.dialog_rename_dataitem_title"), //$NON-NLS-1$
            JOptionPane.QUESTION_MESSAGE, null, null, name);
    return name;/*  ww w.  j  a  v a  2s  . c  om*/
}

From source file:dbseer.gui.panel.DBSeerSelectableChartPanel.java

@Override
public void chartMouseClicked(ChartMouseEvent chartMouseEvent) {
    ChartEntity entity = chartMouseEvent.getEntity();
    MouseEvent mouseEvent = chartMouseEvent.getTrigger();

    if (SwingUtilities.isLeftMouseButton(mouseEvent) && entity != null && entity instanceof PieSectionEntity) {
        java.util.List<String> names = dataset.getTransactionTypeNames();
        PieSectionEntity pieSectionEntity = (PieSectionEntity) entity;
        int idx = pieSectionEntity.getSectionIndex();

        String name = (String) JOptionPane.showInputDialog(null, "Enter the name for this transaction type",
                "Transaction Type", JOptionPane.PLAIN_MESSAGE, null, null, "");

        if (name != null) {
            if (names.contains(name) && !names.get(idx).equals(name) && !name.isEmpty()) {
                JOptionPane.showMessageDialog(null,
                        "Please enter a different name for the transaction type.\nEach name has to be unique.",
                        "Warning", JOptionPane.WARNING_MESSAGE);
            } else {
                PieDataset oldDataset = pieSectionEntity.getDataset();
                DefaultPieDataset newDataset = new DefaultPieDataset();

                PiePlot plot = (PiePlot) chart.getPlot();
                String oldName = (String) oldDataset.getKey(idx);
                names.set(idx, name);/*from   w  w  w  .j  ava  2  s. c  o m*/
                dataset.setTransactionTypeName(idx, name);

                for (int i = 0; i < oldDataset.getItemCount(); ++i) {
                    String key = (String) oldDataset.getKey(i);
                    Number number = oldDataset.getValue(i);

                    if (key.equals(oldName)) {
                        if (name.isEmpty())
                            newDataset.setValue("Transaction Type " + (i + 1), number);
                        else
                            newDataset.setValue(name, number);
                    } else {
                        newDataset.setValue(key, number);
                    }
                }

                Paint[] tempPaint = new Paint[oldDataset.getItemCount()];
                for (int i = 0; i < oldDataset.getItemCount(); ++i) {
                    String key = (String) oldDataset.getKey(i);
                    tempPaint[i] = plot.getSectionPaint(key);
                }

                ((DefaultPieDataset) oldDataset).clear();
                plot.setDataset(newDataset);

                for (int i = 0; i < newDataset.getItemCount(); ++i) {
                    String key = (String) newDataset.getKey(i);
                    plot.setSectionPaint(key, tempPaint[i]);
                }
            }
        }
    }
}

From source file:e3fraud.gui.MainWindow.java

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(MainWindow.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //parse file
            this.baseModel = FileParser.parseFile(file);
            log.append(currentTime.currentTime() + " Opened: " + file.getName() + "." + newline);
        } else {//from  w  ww.  j  ava2  s.  c  o  m
            log.append(currentTime.currentTime() + " Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

        //handle Generate button
    } else if (e.getSource() == generateButton) {
        if (this.baseModel != null) {
            //have the user indicate the ToA via pop-up
            JFrame frame1 = new JFrame("Select Target of Assessment");
            Map<String, Resource> actorsMap = this.baseModel.getActorsMap();
            String selectedActorString = (String) JOptionPane.showInputDialog(frame1,
                    "Which actor's perspective are you taking?", "Choose main actor",
                    JOptionPane.QUESTION_MESSAGE, null, actorsMap.keySet().toArray(),
                    actorsMap.keySet().toArray()[0]);
            if (selectedActorString == null) {
                log.append(currentTime.currentTime() + " Attack generation cancelled!" + newline);
            } else {
                lastSelectedActorString = selectedActorString;
                //have the user select a need via pop-up
                JFrame frame2 = new JFrame("Select graph parameter");
                Map<String, Resource> needsMap = this.baseModel.getNeedsMap();
                String selectedNeedString = (String) JOptionPane.showInputDialog(frame2,
                        "What do you want to use as parameter?", "Choose need to parametrize",
                        JOptionPane.QUESTION_MESSAGE, null, needsMap.keySet().toArray(),
                        needsMap.keySet().toArray()[0]);
                if (selectedNeedString == null) {
                    log.append("Attack generation cancelled!" + newline);
                } else {
                    lastSelectedNeedString = selectedNeedString;
                    //have the user select occurence interval via pop-up
                    JTextField xField = new JTextField("1", 4);
                    JTextField yField = new JTextField("500", 4);
                    JPanel myPanel = new JPanel();
                    myPanel.add(new JLabel("Mininum occurences:"));
                    myPanel.add(xField);
                    myPanel.add(Box.createHorizontalStrut(15)); // a spacer
                    myPanel.add(new JLabel("Maximum occurences:"));
                    myPanel.add(yField);
                    int result = JOptionPane.showConfirmDialog(null, myPanel,
                            "Please Enter occurence rate interval", JOptionPane.OK_CANCEL_OPTION);

                    if (result == JOptionPane.CANCEL_OPTION) {
                        log.append("Attack generation cancelled!" + newline);
                    } else if (result == JOptionPane.OK_OPTION) {
                        startValue = Integer.parseInt(xField.getText());
                        endValue = Integer.parseInt(yField.getText());

                        selectedNeed = needsMap.get(selectedNeedString);
                        selectedActor = actorsMap.get(selectedActorString);

                        //Have a Worker thread to the time-consuming generation and raking (to not freeze the GUI)
                        GenerationWorker generationWorker = new GenerationWorker(baseModel, selectedActorString,
                                selectedActor, selectedNeed, selectedNeedString, startValue, endValue, log,
                                lossButton, gainButton, lossGainButton, gainLossButton, groupingButton,
                                collusionsButton) {
                            //make it so that when Worker is done
                            @Override
                            protected void done() {
                                try {
                                    progressBar.setVisible(false);
                                    System.err.println("I made it invisible");
                                    //the Worker's result is retrieved
                                    treeModel.setRoot(get());
                                    tree.setModel(treeModel);

                                    tree.updateUI();
                                    tree.collapseRow(1);
                                    //tree.expandRow(0);
                                    tree.setRootVisible(false);
                                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                } catch (InterruptedException | ExecutionException ex) {
                                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                    log.append("Out of memory; please increase heap size of JVM");
                                    PopUps.infoBox(
                                            "Encountered an error. Most likely out of memory; try increasing the heap size of JVM",
                                            "Error");
                                }
                            }
                        };
                        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        progressBar.setVisible(true);
                        progressBar.setIndeterminate(true);
                        progressBar.setString("generating...");
                        generationWorker.addPropertyChangeListener(new PropertyChangeListener() {
                            public void propertyChange(PropertyChangeEvent evt) {
                                if ("phase".equals(evt.getPropertyName())) {
                                    progressBar.setMaximum(100);
                                    progressBar.setIndeterminate(false);
                                    progressBar.setString("ranking...");
                                } else if ("progress".equals(evt.getPropertyName())) {
                                    progressBar.setValue((Integer) evt.getNewValue());
                                }
                            }
                        });
                        generationWorker.execute();
                    }
                }
            }
        } else {
            log.append("Load a model file first!" + newline);
        }
    } //handle the refresh button
    else if (e.getSource() == refreshButton) {
        if (lastSelectedNeedString != null && lastSelectedActorString != null) {
            Map<String, Resource> actorsMap = this.baseModel.getActorsMap();
            Map<String, Resource> needsMap = this.baseModel.getNeedsMap();
            selectedNeed = needsMap.get(lastSelectedNeedString);
            selectedActor = actorsMap.get(lastSelectedActorString);

            //Have a Worker thread to the time-consuming generation and raking (to not freeze the GUI)
            GenerationWorker generationWorker = new GenerationWorker(baseModel, lastSelectedActorString,
                    selectedActor, selectedNeed, lastSelectedNeedString, startValue, endValue, log, lossButton,
                    gainButton, lossGainButton, gainLossButton, groupingButton, collusionsButton) {
                //make it so that when Worker is done
                @Override
                protected void done() {
                    try {
                        progressBar.setVisible(false);
                        //the Worker's result is retrieved
                        treeModel.setRoot(get());
                        tree.setModel(treeModel);
                        tree.updateUI();
                        tree.collapseRow(1);
                        //tree.expandRow(0);
                        tree.setRootVisible(false);
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        log.append("Most likely out of memory; please increase heap size of JVM");
                        PopUps.infoBox(
                                "Encountered an error. Most likely out of memory; try increasing the heap size of JVM",
                                "Error");
                    }
                }
            };
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            progressBar.setVisible(true);
            progressBar.setIndeterminate(true);
            progressBar.setString("generating...");
            generationWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("phase".equals(evt.getPropertyName())) {
                        progressBar.setMaximum(100);
                        progressBar.setIndeterminate(false);
                        progressBar.setString("ranking...");
                    } else if ("progress".equals(evt.getPropertyName())) {
                        progressBar.setValue((Integer) evt.getNewValue());
                    }
                }
            });
            generationWorker.execute();

        } else {
            log.append(currentTime.currentTime() + " Nothing to refresh. Generate models first" + newline);
        }

    } //handle show ideal graph button
    else if (e.getSource() == idealGraphButton) {
        if (this.baseModel != null) {
            graph1 = GraphingTool.generateGraph(baseModel, selectedNeed, startValue, endValue, true);//expected graph 
            ChartFrame chartframe1 = new ChartFrame("Ideal results", graph1);
            chartframe1.setPreferredSize(new Dimension(CHART_WIDTH, CHART_HEIGHT));
            chartframe1.pack();
            chartframe1.setLocationByPlatform(true);
            chartframe1.setVisible(true);
        } else {
            log.append(currentTime.currentTime() + " Load a model file first!" + newline);
        }
    } //Handle the graph extend button//Handle the graph extend button
    else if (e.getSource() == expandButton) {
        //make sure there is a graph to show
        if (graph2 == null) {
            log.append(currentTime.currentTime() + " No graph to display. Select one first." + newline);
        } else {
            //this makes sure both graphs have the same y axis:
            //            double lowerBound = min(graph1.getXYPlot().getRangeAxis().getRange().getLowerBound(), graph2.getXYPlot().getRangeAxis().getRange().getLowerBound());
            //            double upperBound = max(graph1.getXYPlot().getRangeAxis().getRange().getUpperBound(), graph2.getXYPlot().getRangeAxis().getRange().getUpperBound());
            //            graph1.getXYPlot().getRangeAxis().setRange(lowerBound, upperBound);
            //            graph2.getXYPlot().getRangeAxis().setRange(lowerBound, upperBound);
            chartPane.removeAll();
            chartPanel = new ChartPanel(graph2);
            chartPanel.setPreferredSize(new Dimension(CHART_WIDTH, CHART_HEIGHT));
            chartPane.add(chartPanel);
            chartPane.add(collapseButton);
            extended = true;
            this.setPreferredSize(new Dimension(this.getWidth() + CHART_WIDTH, this.getHeight()));
            JFrame frame = (JFrame) getRootPane().getParent();
            frame.pack();
        }
    } //Handle the graph collapse button//Handle the graph collapse button
    else if (e.getSource() == collapseButton) {
        System.out.println("resizing by -" + CHART_WIDTH);
        chartPane.removeAll();
        chartPane.add(expandButton);
        this.setPreferredSize(new Dimension(this.getWidth() - CHART_WIDTH, this.getHeight()));
        chartPane.repaint();
        chartPane.revalidate();
        extended = false;
        JFrame frame = (JFrame) getRootPane().getParent();
        frame.pack();
    }
}

From source file:gda.gui.mca.McaGUI.java

private SimplePlot getSimplePlot() {
    if (simplePlot == null) {
        simplePlot = new SimplePlot();
        simplePlot.setYAxisLabel("Values");
        simplePlot.setTitle("MCA");
        /*/*w w w  . jav  a  2s. co m*/
         * do not attempt to get calibration until the analyser is available getEnergyCalibration();
         */

        simplePlot.setXAxisLabel("Channel Number");

        simplePlot.setTrackPointer(true);
        JPopupMenu menu = simplePlot.getPopupMenu();
        JMenuItem item = new JMenuItem("Add Region Of Interest");
        menu.add(item);
        item.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "To add a region of interest, please click on region low"
                        + " and region high channels\n" + "in the graph and set the index\n");
                regionClickCount = 0;
            }
        });

        JMenuItem calibitem = new JMenuItem("Calibrate Energy");
        /*
         * Comment out as calibration is to come from the analyser directly menu.add(calibitem);
         */
        calibitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // regionClickCount = 0;
                    int[] data = (int[]) analyser.getData();
                    double[] dData = new double[data.length];
                    for (int i = 0; i < dData.length; i++) {
                        dData[i] = data[i];
                    }
                    if (energyCalibrationDialog == null) {
                        energyCalibrationDialog = new McaCalibrationPanel(
                                (EpicsMCARegionOfInterest[]) analyser.getRegionsOfInterest(), dData, mcaName);
                        energyCalibrationDialog.addIObserver(McaGUI.this);
                    }
                    energyCalibrationDialog.setVisible(true);
                } catch (DeviceException e1) {
                    logger.error("Exception: " + e1.getMessage());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                    ex.printStackTrace();
                }
            }

        });

        simplePlot.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent me) {
                // /////////System.out.println("Mouse clicked " +
                // me.getX() + " "
                // /////// + me.getY());
                SimpleDataCoordinate coordinates = simplePlot.convertMouseEvent(me);
                if (simplePlot.getScreenDataArea().contains(me.getX(), me.getY()) && regionClickCount == 0) {
                    regionLow = coordinates.toArray();
                    regionClickCount++;
                } else if (simplePlot.getScreenDataArea().contains(me.getX(), me.getY())
                        && regionClickCount == 1) {
                    regionHigh = coordinates.toArray();
                    regionClickCount++;

                    if (regionValid(regionLow[0], regionHigh[0])) {

                        final String s = (String) JOptionPane.showInputDialog(null,
                                "Please select the Region Index:\n", "Region Of Interest",
                                JOptionPane.PLAIN_MESSAGE, null, null, String.valueOf(getNextRegion()));
                        Thread t1 = uk.ac.gda.util.ThreadManager.getThread(new Runnable() {
                            @Override
                            public void run() {

                                try {

                                    if (s != null) {
                                        int rIndex = Integer.parseInt(s);
                                        EpicsMCARegionOfInterest[] epc = { new EpicsMCARegionOfInterest() };
                                        epc[0].setRegionLow(regionLow[0]);
                                        epc[0].setRegionHigh(regionHigh[0]);
                                        epc[0].setRegionIndex(rIndex);
                                        epc[0].setRegionName("region " + rIndex);
                                        analyser.setRegionsOfInterest(epc);

                                        addRegionMarkers(rIndex, regionLow[0], regionHigh[0]);
                                    }

                                } catch (DeviceException e) {
                                    logger.error("Unable to set the table values");
                                }

                            }

                        });
                        t1.start();
                    }
                }
            }

        });

        // TODO note that selectePlot cannot be changed runtime
        simplePlot.initializeLine(selectedPlot);
        simplePlot.setLineName(selectedPlot, getSelectedPlotString());
        simplePlot.setLineColor(selectedPlot, getSelectedPlotColor());
        simplePlot.setLineType(selectedPlot, "LineOnly");

    }
    return simplePlot;
}

From source file:org.rdv.viz.chart.ChartViz.java

/**
 * Add data from a local file as a series to this chart. This will ask the
 * user for the file name, and which channels to use.
 *///from ww  w . j a  v  a 2 s .co m
private void addLocalSeries() {
    File file = UIUtilities.openFile();
    if (file == null || !file.isFile() || !file.exists()) {
        return;
    }

    DataFileReader reader;
    try {
        reader = new DataFileReader(file);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(getDataComponent(), e.getMessage(), "Problem reading data file",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    List<Channel> channels = reader.getChannels();
    if (channels.size() < 2) {
        JOptionPane.showMessageDialog(getDataComponent(), "There must be at least 2 channels in the data file",
                "Problem with data file", JOptionPane.ERROR_MESSAGE);
        return;
    }

    Channel xChannel;
    Channel yChannel;

    if (channels.size() == 2) {
        xChannel = channels.get(0);
        yChannel = channels.get(1);
    } else {
        xChannel = (Channel) JOptionPane.showInputDialog(getDataComponent(), "Select the x channel:",
                "Add local channel", JOptionPane.PLAIN_MESSAGE, null, channels.toArray(), null);

        if (xChannel == null) {
            return;
        }

        yChannel = (Channel) JOptionPane.showInputDialog(getDataComponent(), "Select the y channel:",
                "Add local channel", JOptionPane.PLAIN_MESSAGE, null, channels.toArray(), null);

        if (yChannel == null) {
            return;
        }
    }

    String xChannelName = xChannel.getName();
    if (xChannel.getUnit() != null) {
        xChannelName += " (" + xChannel.getUnit() + ")";
    }
    int xChannelIndex = channels.indexOf(xChannel);

    String yChannelName = yChannel.getName();
    if (yChannel.getUnit() != null) {
        yChannelName += " (" + yChannel.getUnit() + ")";
    }
    int yChannelIndex = channels.indexOf(yChannel);

    String seriesName = xChannelName + " vs. " + yChannelName;

    XYTimeSeries data = new XYTimeSeries(seriesName, FixedMillisecond.class);

    try {
        NumericDataSample sample;
        while ((sample = reader.readSample()) != null) {
            double timestamp = sample.getTimestamp();
            Number[] values = sample.getValues();

            FixedMillisecond time = new FixedMillisecond((long) (timestamp * 1000));
            XYTimeSeriesDataItem dataItem = new XYTimeSeriesDataItem(time);

            if (values[xChannelIndex] != null && values[yChannelIndex] != null) {
                dataItem.setX(values[xChannelIndex]);
                dataItem.setY(values[yChannelIndex]);
            }

            data.add(dataItem, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    Color color = getLeastUsedColor();
    colors.put(seriesName, color);

    ((XYTimeSeriesCollection) dataCollection).addSeries(data);
    localSeries++;

    setSeriesColors();

    updateTitle();

    updateLegend();
}

From source file:Debrief.Tools.FilterOperations.ShowTimeVariablePlot3.java

private CalculationHolder getChoice() {
    final Object[] opts = new Object[_theOperations.size()];
    _theOperations.copyInto(opts);//from   w  w  w .j av a  2 s .co  m
    final CalculationHolder res = (CalculationHolder) JOptionPane.showInputDialog(null, "Which operation?",
            "Plot time variables", JOptionPane.QUESTION_MESSAGE, null, opts, null);
    return res;
}

From source file:lu.fisch.moenagade.model.Project.java

public BloxsClass renameWorld(World world) {
    String name = world.getName();
    boolean result;

    do {/*www . ja  va 2s.  co m*/
        name = (String) JOptionPane.showInputDialog(frame, "Please enter the world's new name.", "Rename world",
                JOptionPane.PLAIN_MESSAGE, null, null, name);

        if (name == null)
            return null;

        result = true;

        // check if name is OK
        Matcher matcher = Pattern.compile("^[a-zA-Z_$][a-zA-Z_$0-9]*$").matcher(name);
        boolean found = matcher.find();
        if (!found) {
            result = false;
            JOptionPane.showMessageDialog(frame, "Please chose a valid name.", "Error",
                    JOptionPane.ERROR_MESSAGE, Moenagade.IMG_ERROR);
        }
        // check if name is unique
        else if (worlds.containsKey(name)) {
            result = false;
            JOptionPane.showMessageDialog(frame, "This name is not unique.", "Error", JOptionPane.ERROR_MESSAGE,
                    Moenagade.IMG_ERROR);
        }
        // check internal name
        else if (name.trim().equals("World")) {
            result = false;
            JOptionPane.showMessageDialog(frame,
                    "The name \"World\" is already internaly\nused and thus not allowed!", "Error",
                    JOptionPane.ERROR_MESSAGE, Moenagade.IMG_ERROR);
        } else if (name.charAt(0) != name.toUpperCase().charAt(0)) {
            result = false;
            JOptionPane.showMessageDialog(frame, "The name should start with a capital letter.", "Error",
                    JOptionPane.ERROR_MESSAGE, Moenagade.IMG_ERROR);
        } else {
            // send refresh
            refresh(new Change(null, -1, "rename.world", world.getName(), name));
            // switch 
            worlds.remove(world.getName());
            worlds.put(name, world);
            // rename file (if present)
            File fFrom = new File(directoryName + System.getProperty("file.separator") + "bloxs"
                    + System.getProperty("file.separator") + "worlds" + System.getProperty("file.separator")
                    + world.getName() + ".bloxs");
            File fTo = new File(directoryName + System.getProperty("file.separator") + "bloxs"
                    + System.getProperty("file.separator") + "worlds" + System.getProperty("file.separator")
                    + name + ".bloxs");
            if (fFrom.exists())
                fFrom.renameTo(fTo);
            // do the rename
            world.setName(name);
            return world;
        }
    } while (!result);

    return null;
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Changes the font size to what the user selects (between 8-30)
 *///from   w  w  w.  j  a va 2 s  .  co m
private void changeFontSize() {
    Integer[] nums = new Integer[23];
    for (int i = 8; i <= 30; i++) {
        nums[i - 8] = i;
    }
    try {
        int size = (int) JOptionPane.showInputDialog(this, "Choose a font size:", "Font Size",
                JOptionPane.PLAIN_MESSAGE, null, nums, Main.getState().getSettings().getFontSize());
        FontUIResource font = new FontUIResource("Dialog", Font.BOLD, size);

        Main.setUIFont(font);
        Main.getState().getSettings().setFontSize(size);
        SwingUtilities.updateComponentTreeUI(gr);

        for (JInternalFrame i : desktop.getAllFrames())
            i.pack();

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:it.imtech.configuration.StartWizard.java

/**
 * Retrieve online configuration filepath
 *
 * @throws MalformedURLException/*  w w  w. j a v  a 2 s.  c  o  m*/
 * @throws ConfigurationException
 */
private XMLConfiguration setConfigurationPaths(XMLConfiguration internalConf, ResourceBundle bundle) {
    XMLConfiguration configuration = null;

    try {
        String text = Utility.getBundleString("setconf", bundle);
        String title = Utility.getBundleString("setconf2", bundle);

        internalConf.setAutoSave(true);

        String n = internalConf.getString("configurl[@path]");

        if (n.isEmpty()) {
            String s = (String) JOptionPane.showInputDialog(new Frame(), text, title, JOptionPane.PLAIN_MESSAGE,
                    null, null, "http://phaidrastatic.cab.unipd.it/xml/config.xml");

            //If a string was returned, say so.
            if ((s != null) && (s.length() > 0)) {
                internalConf.setProperty("configurl[@path]", s);
                Globals.URL_CONFIG = new URL(s);
            } else {
                logger.info("File di configurazione non settato");
            }
        } else {
            if (Globals.ONLINE) {
                Globals.URL_CONFIG = new URL(n);
            }
        }

        if (Globals.URL_CONFIG != null) {
            if (Globals.DEBUG)
                configuration = new XMLConfiguration(new File(Globals.JRPATH + Globals.DEBUG_XML));
            else
                configuration = new XMLConfiguration(Globals.URL_CONFIG);
        } else {
            if (!Globals.ONLINE) {
                configuration = new XMLConfiguration(
                        new File(Globals.USER_DIR + Utility.getSep() + Globals.FOLD_XML + "config.xml"));
            }
        }
    } catch (final MalformedURLException ex) {
        logger.error(ex.getMessage());
        JOptionPane.showMessageDialog(new Frame(), Utility.getBundleString("exc_conf_1", bundle));
    } catch (final ConfigurationException ex) {
        logger.error(ex.getMessage());
        JOptionPane.showMessageDialog(new Frame(), Utility.getBundleString("exc_conf_2", bundle));
    }

    return configuration;
}

From source file:edu.harvard.i2b2.query.QueryTopPanel.java

private void jRunQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {
    //System.out.println("value set on the slider: "+ jSlider1.getValue());
    if (dataModel.isAllPanelEmpty()) {
        JOptionPane.showMessageDialog(this, "All groups are empty.");
        return;//  w  w  w.j  a  v  a  2 s.c  o m
    }

    String queryNametmp = jNameTextField.getText();
    //if(queryNametmp.equals("") || queryNametmp == null) {
    queryNametmp = dataModel.getTmpQueryName();
    //}
    Object selectedValue = JOptionPane.showInputDialog(this, "Please supply a name for this query: ",
            "Query Name Dialog", JOptionPane.PLAIN_MESSAGE, null, null, queryNametmp);

    if (selectedValue == null) {
        return;
    } else {
        queryNametmp = (String) selectedValue;
    }

    dataModel.queryName(queryNametmp);
    final String queryName = queryNametmp;
    //System.out.println("Provided query name: " + queryName);

    ImageIcon buttonIcon = createImageIcon("indicator_18.gif");
    this.jRunQueryButton.setIcon(buttonIcon);
    this.jRunQueryButton.setText("         Running ......");
    final Color defaultcolor = jRunQueryButton.getBackground();

    dataModel.specificity(0);//jSlider1.getValue());
    final String xmlStr = dataModel.wirteQueryXML();
    parentPanel.lastRequestMessage(xmlStr);
    parentPanel.setPatientCount("");
    parentPanel.setRequestText(xmlStr);
    parentPanel.setResponseText("Waiting for response ...");
    //System.out.println("Query request: "+xmlStr);
    jNameTextField.setText(queryName);

    queryThread = new Thread() {
        public void run() {
            //setCursor(new Cursor(Cursor.WAIT_CURSOR));
            response = QueryRequestClient.sendQueryRequestREST(xmlStr);
            parentPanel.lastResponseMessage(response);
            if (response != null) {
                //response = response.substring(response.indexOf("<ns2:response"), response.indexOf("</i2b2:response>"));
                parentPanel.setResponseText(response);
                JAXBUtil jaxbUtil = QueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    BodyType bt = messageType.getMessageBody();
                    MasterInstanceResultResponseType masterInstanceResultResponseType = (MasterInstanceResultResponseType) new JAXBUnWrapHelper()
                            .getObjectByClass(bt.getAny(), MasterInstanceResultResponseType.class);
                    String queryId = null;
                    //ResponseMessageType messageType = jaxbUtil.unMashallResponseMessageTypeFromString(response);
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();
                    queryId = new Integer(masterInstanceResultResponseType.getQueryMaster().getQueryMasterId())
                            .toString();//messageType.getResponseHeader().getInfo().getValue();
                    //System.out.println("Get query id: "+queryId);

                    QueryMasterData nameNode = new QueryMasterData();
                    nameNode.name(queryName);
                    nameNode.visualAttribute("CA");
                    nameNode.userId(UserInfoBean.getInstance().getUserName());
                    nameNode.tooltip("A query run by " + nameNode.userId());
                    nameNode.id(queryId);
                    //nameNode.xmlContent(xmlStr);

                    String count = "";
                    if (status.equalsIgnoreCase("DONE")) {
                        String refId = null;
                        try {
                            edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.StatusType cellStatusType = masterInstanceResultResponseType
                                    .getStatus();
                            if (cellStatusType.getCondition().get(0).getValue().equalsIgnoreCase("RUNNING")) {
                                JOptionPane.showMessageDialog(parentPanel,
                                        "Query is still running, you may check its status later \n"
                                                + "in the previous queries view by right clicking on a node\n"
                                                + "then selecting refresh all.");
                                jRunQueryButton.setIcon(null);
                                jRunQueryButton.setText("Run Query");
                                return;
                            } else if (cellStatusType.getCondition().get(0).getValue()
                                    .equalsIgnoreCase("ERROR")) {
                                JOptionPane.showMessageDialog(parentPanel,
                                        "Error message delivered from the remote server, "
                                                + "you may wish to retry your last action");
                                jRunQueryButton.setIcon(null);
                                jRunQueryButton.setText("Run Query");
                                return;
                            }

                            QueryResultInstanceType queryResultInstanceType = masterInstanceResultResponseType
                                    .getQueryResultInstance().get(0);
                            refId = new Integer(queryResultInstanceType.getResultInstanceId()).toString();
                            //System.out.println("Set Ref id: "+ refId);
                            count = new Integer(queryResultInstanceType.getSetSize()).toString();
                            parentPanel.setPatientCount(count);
                        } catch (Exception e) {
                            e.printStackTrace();
                            JOptionPane.showMessageDialog(parentPanel,
                                    "Response delivered from the remote server could not be understood,\n"
                                            + "you may wish to retry your last action.");

                            jRunQueryButton.setIcon(null);
                            jRunQueryButton.setText("Run Query");
                            return;
                        }

                        IWorkbenchPage page = ((QueryPanelInvestigator) parentPanel).parentview.getViewSite()
                                .getPage();
                        ViewPart previousqueryview = (ViewPart) page.findView(
                                "edu.harvard.i2b2.eclipse.plugins.previousquery.views.PreviousQueryView");
                        ((ICommonMethod) previousqueryview).doSomething(nameNode.name() + " ["
                                + dataModel.getDayString() + "]" + "#i2b2seperater#" + nameNode.id());

                        ArrayList<String> nodeXmls = new ArrayList<String>();
                        for (int i = 0; i < dataModel.getCurrentPanelCount(); i++) {
                            ArrayList<QueryConceptTreeNodeData> nodelist = dataModel.getTreePanel(i).getItems();
                            for (int j = 0; j < nodelist.size(); j++) {
                                QueryConceptTreeNodeData nodedata = nodelist.get(j);
                                String termStatus = nodedata.setXmlContent();
                                if (termStatus.equalsIgnoreCase("error")) {
                                    JOptionPane.showMessageDialog(parentPanel,
                                            "Response delivered from the remote server could not be understood,\n"
                                                    + "you may wish to retry your last action.");
                                    jRunQueryButton.setIcon(null);
                                    jRunQueryButton.setText("Run Query");
                                    return;
                                }
                                nodeXmls.add(nodedata.xmlContent());
                            }
                        }

                        ViewPart explorerview = (ViewPart) page
                                .findView("edu.harvard.i2b2.eclipse.plugins.explorer.views.ExplorerView");
                        String str1 = "" + count;
                        String str2 = "-" + refId;
                        ((ICommonMethod) explorerview).doSomething(str1 + str2);
                        ((ICommonMethod) explorerview).doSomething(nodeXmls);
                    } else {
                        JOptionPane.showMessageDialog(parentPanel,
                                "Error message delivered from the remote server, "
                                        + "you may wish to retry your last action");

                        jRunQueryButton.setIcon(null);
                        jRunQueryButton.setText("Run Query");
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(parentPanel,
                            "Response delivered from the remote server could not be understood,\n"
                                    + "you may wish to retry your last action.");
                    jRunQueryButton.setIcon(null);
                    jRunQueryButton.setText("Run Query");
                    return;
                }
            }
            //setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            jRunQueryButton.setIcon(null);
            jRunQueryButton.setText("Run Query");
            //jRunQueryButton.setBackground(defaultcolor);
        }
    };

    try {
        queryThread.start();
    } catch (Exception e) {
        e.printStackTrace();
        parentPanel.setResponseText(e.getMessage());
    }
}