Example usage for javax.swing JOptionPane CANCEL_OPTION

List of usage examples for javax.swing JOptionPane CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

To view the source code for javax.swing JOptionPane CANCEL_OPTION.

Click Source Link

Document

Return value from class method if CANCEL is chosen.

Usage

From source file:com.sshtools.tunnel.PortForwardingPane.java

protected void editPortForward() {

    ForwardingConfiguration config = model.getForwardingConfigurationAt(table.getSelectedRow());
    if (config.getName().equals("x11")) {
        JOptionPane.showMessageDialog(this, "You cannot edit X11 forwarding.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;//from   w w w  .java2 s .  c o m
    }
    PortForwardEditorPane editor = new PortForwardEditorPane(config);

    int option = JOptionPane.showConfirmDialog(this, editor, "Edit Tunnel", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (option != JOptionPane.CANCEL_OPTION && option != JOptionPane.CLOSED_OPTION) {
        try {
            ForwardingClient forwardingClient = client;
            String id = editor.getForwardName();
            if (id.equals("x11")) {
                throw new Exception("The id of x11 is reserved.");
            }
            if (editor.getHost().equals("")) {
                throw new Exception("Please specify a destination host.");
            }
            int i = model.getRowCount();
            if (editor.isLocal()) {
                forwardingClient.removeLocalForwarding(config.getName());
                forwardingClient.addLocalForwarding(id, editor.getBindAddress(), editor.getLocalPort(),
                        editor.getHost(), editor.getRemotePort());
                forwardingClient.startLocalForwarding(id);
            } else {
                forwardingClient.removeRemoteForwarding(config.getName());
                forwardingClient.addRemoteForwarding(id, editor.getBindAddress(), editor.getLocalPort(),
                        editor.getHost(), editor.getRemotePort());
                forwardingClient.startRemoteForwarding(id);
            }

            if (i < model.getRowCount()) {
                table.getSelectionModel().addSelectionInterval(i, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            model.refresh();
            sessionPanel.setAvailableActions();
        }
    }
}

From source file:imageviewer.system.ImageViewerClient.java

private void initialize(CommandLine args) {

    // First, process all the different command line arguments that we
    // need to override and/or send onwards for initialization.

    boolean fullScreen = (args.hasOption("fullscreen")) ? true : false;
    String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null;
    String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM";
    String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null;

    LOG.info("Java home environment: " + System.getProperty("java.home"));

    // Logging system taken care of through properties file.  Check
    // for JAI.  Set up JAI accordingly with the size of the cache
    // tile and to recycle cached tiles as needed.

    verifyJAI();/*w w w.ja v  a 2s.  co m*/
    TileCache tc = JAI.getDefaultInstance().getTileCache();
    tc.setMemoryCapacity(32 * 1024 * 1024);
    TileScheduler ts = JAI.createTileScheduler();
    ts.setPriority(Thread.MAX_PRIORITY);
    JAI.getDefaultInstance().setTileScheduler(ts);
    JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);

    // Set up the frame and everything else.  First, try and set the
    // UI manager to use our look and feel because it's groovy and
    // lets us control the GUI components much better.

    try {
        UIManager.setLookAndFeel(new ImageViewerLookAndFeel());
        LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class);
    } catch (Exception exc) {
        LOG.error("Could not set imageViewer L&F.");
    }

    // Load up the ApplicationContext information...

    ApplicationContext ac = ApplicationContext.getContext();
    if (ac == null) {
        LOG.error("Could not load configuration, exiting.");
        System.exit(1);
    }

    // Override the client node information based on command line
    // arguments...Make sure that the files are there, otherwise just
    // default to a local configuration.

    String hostname = new String("localhost");
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception exc) {
    }

    String[] gatewayConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" });
    String[] nodeConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml",
                    "resources/server/localNodeConfig.xml" });

    for (int loop = 0; loop < gatewayConfigs.length; loop++) {
        String s = gatewayConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s);
                break;
            }
        }
    }

    LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG));

    for (int loop = 0; loop < nodeConfigs.length; loop++) {
        String s = nodeConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s);
                break;
            }
        }
    }
    LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE));

    // Load the layouts and set the default window/level manager...

    LayoutFactory.initialize();
    DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager();

    // Create the main JFrame, set its behavior, and let the
    // ApplicationPanel know the glassPane and layeredPane.  Set the
    // menubar based on reading in the configuration menus.

    mainFrame = new JFrame("imageviewer");
    try {
        ArrayList<Image> iconList = new ArrayList<Image>();
        iconList.add(ImageIO.read(new File("resources/icons/mii.png")));
        iconList.add(ImageIO.read(new File("resources/icons/mii32.png")));
        mainFrame.setIconImages(iconList);
    } catch (Exception exc) {
    }

    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            int confirm = ApplicationPanel.getInstance().showDialog(
                    "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon"));
            if (confirm == JOptionPane.OK_OPTION) {
                boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems();
                if (hasUnsaved) {
                    int saveResult = ApplicationPanel.getInstance().showDialog(
                            "There is still unsaved data.  Do you want to save this data in the local archive?",
                            null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
                    if (saveResult == JOptionPane.CANCEL_OPTION)
                        return;
                    if (saveResult == JOptionPane.YES_OPTION)
                        SaveStack.getInstance().saveAll();
                }
                LOG.info("Shutting down imageServer local archive...");
                try {
                    ImageViewerClientNode.getInstance().shutdown();
                } catch (Exception exc) {
                    LOG.error("Problem shutting down imageServer local archive...");
                } finally {
                    System.exit(0);
                }
            }
        }
    });

    String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS);
    String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON);
    if (menuFile != null) {
        JMenuBar mb = new JMenuBar();
        mb.setBackground(Color.black);
        MenuReader.parseFile(menuFile, mb);
        mainFrame.setJMenuBar(mb);
        ApplicationContext.getContext().setApplicationMenuBar(mb);
    } else if (ribbonFile != null) {
        RibbonReader rr = new RibbonReader();
        JRibbon jr = rr.parseFile(ribbonFile);
        mainFrame.getContentPane().add(jr, BorderLayout.NORTH);
        ApplicationContext.getContext().setApplicationRibbon(jr);
    }
    mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER);
    ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane()));
    ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane());

    // Load specified plugins...has to occur after the menus are
    // created, btw.

    PluginLoader.initialize("config/plugins.xml");

    // Detect operating system...

    String osName = System.getProperty("os.name");
    ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName);
    LOG.info("Detected operating system: " + osName);

    // Try and hack the searched library paths if it's windows so we
    // can add a local dll path...

    try {
        if (osName.contains("Windows")) {
            Field f = ClassLoader.class.getDeclaredField("usr_paths");
            f.setAccessible(true);
            String[] paths = (String[]) f.get(null);
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            File currentPath = new File(".");
            tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/";
            f.set(null, tmp);
            f.setAccessible(false);
        }
    } catch (Exception exc) {
        LOG.error("Error attempting to dynamically set library paths.");
    }

    // Get screen resolution...

    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();
    Rectangle r = gc.getBounds();
    LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight());

    // Try and see if Java3D is installed, and if so, what version...

    try {
        VirtualUniverse vu = new VirtualUniverse();
        Map m = vu.getProperties();
        String s = (String) m.get("j3d.version");
        LOG.info("Detected Java3D version: " + s);
    } catch (Throwable t) {
        LOG.info("Unable to detect Java3D installation");
    }

    // Try and see if native JOGL is installed...

    try {
        System.loadLibrary("jogl");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE);
        LOG.info("Detected native libraries for JOGL");
    } catch (Throwable t) {
        LOG.info("Unable to detect native JOGL installation");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE);
    }

    // Start the local client node to connect to the network and the
    // local archive running on this machine...Thread the connection
    // process so it doesn't block the imageViewerClient creating this
    // instance.  We may not be connected to the given gateway, so the
    // socketServer may go blah...

    final boolean useNetwork = (args.hasOption("nonet")) ? false : true;
    ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait...");
    if (useNetwork)
        LOG.info("Starting imageServer client to join network - please wait...");
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ImageViewerClientNode.getInstance(
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                        useNetwork);
                ApplicationPanel.getInstance().addStatusMessage("Ready");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });
    t.setPriority(9);
    t.start();

    this.fullScreen = fullScreen;
    mainFrame.setUndecorated(fullScreen);

    // Set the view to encompass the default screen.

    if (fullScreen) {
        Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        mainFrame.setLocation(r.x + i.left, r.y + i.top);
        mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom);
    } else {
        mainFrame.setSize(1100, 800);
        mainFrame.setLocation(r.x + 200, r.y + 100);
    }

    if (dir != null)
        ApplicationPanel.getInstance().load(dir, type);

    timer = new Timer();
    timer.schedule(new GarbageCollectionTimer(), 5000, 2500);
    mainFrame.setVisible(true);
}

From source file:net.sf.jabref.external.DroppedFileHandler.java

private boolean tryXmpImport(String fileName, ExternalFileType fileType, NamedCompound edits) {

    if (!"pdf".equals(fileType.getExtension())) {
        return false;
    }//from w ww.  j a  v a2 s  . c om

    List<BibEntry> xmpEntriesInFile;
    try {
        xmpEntriesInFile = XMPUtil.readXMP(fileName, Globals.prefs);
    } catch (IOException e) {
        LOGGER.warn("Problem reading XMP", e);
        return false;
    }

    if ((xmpEntriesInFile == null) || xmpEntriesInFile.isEmpty()) {
        return false;
    }

    JLabel confirmationMessage = new JLabel(Localization.lang("The PDF contains one or several BibTeX-records.")
            + "\n"
            + Localization.lang("Do you want to import these as new entries into the current database?"));

    int reply = JOptionPane.showConfirmDialog(frame, confirmationMessage,
            Localization.lang("XMP-metadata found in PDF: %0", fileName), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (reply == JOptionPane.CANCEL_OPTION) {
        return true; // The user canceled thus that we are done.
    }
    if (reply == JOptionPane.NO_OPTION) {
        return false;
    }

    // reply == JOptionPane.YES_OPTION)

    /*
     * TODO Extract Import functionality from ImportMenuItem then we could
     * do:
     *
     * ImportMenuItem importer = new ImportMenuItem(frame, (mainTable ==
     * null), new PdfXmpImporter());
     *
     * importer.automatedImport(new String[] { fileName });
     */

    boolean isSingle = xmpEntriesInFile.size() == 1;
    BibEntry single = isSingle ? xmpEntriesInFile.get(0) : null;

    boolean success = true;

    String destFilename;

    if (linkInPlace.isSelected()) {
        destFilename = FileUtil
                .shortenFileName(new File(fileName), panel.getBibDatabaseContext().getFileDirectory())
                .toString();
    } else {
        if (renameCheckBox.isSelected()) {
            destFilename = fileName;
        } else {
            destFilename = single.getCiteKey() + "." + fileType.getExtension();
        }

        if (copyRadioButton.isSelected()) {
            success = doCopy(fileName, destFilename, edits);
        } else if (moveRadioButton.isSelected()) {
            success = doMove(fileName, destFilename, edits);
        }
    }
    if (success) {

        for (BibEntry aXmpEntriesInFile : xmpEntriesInFile) {

            aXmpEntriesInFile.setId(IdGenerator.next());
            edits.addEdit(new UndoableInsertEntry(panel.getDatabase(), aXmpEntriesInFile, panel));
            panel.getDatabase().insertEntry(aXmpEntriesInFile);
            doLink(aXmpEntriesInFile, fileType, destFilename, true, edits);

        }
        panel.markBaseChanged();
        panel.updateEntryEditorIfShowing();
    }
    return true;
}

From source file:be.ugent.maf.cellmissy.gui.controller.load.generic.DragAndDropController.java

/**
 * Action on drop onto the target component: 1. get the wellGui
 * correspondent to the drop-point location; 2. validate this wellGui; 3.
 * check if the well has already some data. If this is not the case, just
 * load new data into it, otherwise, ask the user how to proceed. In this
 * last case, 3 things are possible: 1. Overwrite the data (drag&drop was
 * wrong, e;g.); 2. Clear data for the well (just reset the well); 3. Add
 * more data to the well (same combination of algorithm-imaging type: a new
 * location)./* w  w  w  . ja  v  a 2 s . c o m*/
 *
 * @param point
 * @param node
 */
private void actionOnDrop(Point point, DefaultMutableTreeNode node) {
    WellGui wellGuiDropTarget = getWellGuiDropTarget(point);
    if (wellGuiDropTarget != null) {
        if (validateDropTarget(wellGuiDropTarget)) {
            // new wellHasImagingType (for selected well and current imaging type/algorithm)
            WellHasImagingType newWellHasImagingType = new WellHasImagingType(wellGuiDropTarget.getWell(),
                    currentImagingType, currentAlgorithm);
            // get the list of WellHasImagingType for the selected well
            List<WellHasImagingType> wellHasImagingTypeList = wellGuiDropTarget.getWell()
                    .getWellHasImagingTypeList();
            // check if the wellHasImagingType was already processed
            // this is comparing objects with column, row numbers, and algorithm,imaging types
            if (!wellHasImagingTypeList.contains(newWellHasImagingType)) {
                genericImagedPlateController.loadData(getDataFile(node), newWellHasImagingType,
                        wellGuiDropTarget);
                // update relation with algorithm and imaging type
                currentAlgorithm.getWellHasImagingTypeList().add(newWellHasImagingType);
                currentImagingType.getWellHasImagingTypeList().add(newWellHasImagingType);
                // highlight imaged well
                highlightImagedWell(wellGuiDropTarget);
            } else {
                // warn the user that data was already loaded for the selected combination of well/dataset/imaging type
                Object[] options = { "Overwrite", "Add location on same well", "Clear data for this well",
                        "Cancel" };
                int showOptionDialog = JOptionPane.showOptionDialog(null,
                        "Data already loaded for this well / dataset / imaging type.\nWhat do you want to do now?",
                        "", JOptionPane.CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[3]);
                switch (showOptionDialog) {
                case 0: // overwrite loaded data:
                    genericImagedPlateController.overwriteDataForWell(getDataFile(node), wellGuiDropTarget,
                            newWellHasImagingType);
                    break;
                case 1: // add location on the same well:
                    genericImagedPlateController.loadData(getDataFile(node), newWellHasImagingType,
                            wellGuiDropTarget);
                    break;
                case 2: // clear data for current well
                    genericImagedPlateController.clearDataForWell(wellGuiDropTarget);
                    break;
                //cancel: do nothing
                }
            }
        } else {
            //show a warning message
            String message = "The well you selected does not belong to a condition.\nPlease drag somewhere else!";
            genericImagedPlateController.showMessage(message, "Well's selection error",
                    JOptionPane.WARNING_MESSAGE);
        }
    }
}

From source file:net.sf.jabref.exporter.SaveDatabaseAction.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;//from w w w  . ja  va  2 s  .c o m
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), prefs,
                    panel.getSelectedEntries());

        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.mainTable.findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.mainTable.setRowSelectionInterval(row, row);
            panel.mainTable.scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file);
            panel.setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file);
            panel.setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:electroStaticUI.UserInput.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void getChargeData() {
    numberOfCharges = Integer.parseInt(getNumberOfCharges.getText());
    DefaultValues.allocatePointChargeArray(numberOfCharges);
    chargesToCalc = new PointCharge[numberOfCharges];
    mapper = new CustomMapper(DefaultValues.getCircOrRect());
    chargeDataFrame = new JFrame();
    chargeDataFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JPanel chargeDataPanel = new JPanel();
    chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes));
    JLabel chargeLabel = new JLabel("Charge");
    JLabel chargeUnitLabel = new JLabel("C");
    charge = new JTextField(10);
    charge.setEditable(true);/* w  w w.java 2s  .c o  m*/
    chargeModComboBox = new JComboBox(chargeModList);
    chargeModComboBox.setSelectedIndex(5);
    chargeModComboBox.setVisible(true);
    JLabel xPositionLabel = new JLabel("X Value");
    xPosition = new JTextField(10);
    xPosition.setEditable(true);
    JLabel yPositionLabel = new JLabel("Y Value");
    yPosition = new JTextField(10);
    yPosition.setEditable(true);
    //JLabel zPositionLabel = new JLabel("Z Value");
    //JTextField zPosition = new JTextField(5);
    //zPosition.setEditable(true);
    JButton okButton = new JButton("OK");
    chargeDataPanel.add(chargeLabel);
    chargeDataPanel.add(charge);
    chargeDataPanel.add(chargeModComboBox);
    chargeDataPanel.add(chargeUnitLabel);
    chargeDataPanel.add(xPositionLabel);
    chargeDataPanel.add(xPosition);
    chargeDataPanel.add(yPositionLabel);
    chargeDataPanel.add(yPosition);
    chargeDataPanel.add(okButton);
    chargeDataPanel.setMinimumSize(new Dimension(600, 100));
    chargeDataPanel.setVisible(true);
    chargeDataFrame.add(chargeDataPanel);
    chargeDataFrame.setVisible(true);
    chargeDataFrame.setMinimumSize(new Dimension(600, 100));
    xPosition.setText("0");
    yPosition.setText("0");
    charge.setText("0");
    /*
     * okButton anonymous action listener takes the data entered into the JTextfields and creates point charges from it.
     */
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //do {
            //chargesToCalc[okButtonPushes] = new PointCharge(Double.parseDouble(charge.getText()), Double.parseDouble(xPosition.getText()), Double.parseDouble(yPosition.getText()));
            int chargeModIndex = chargeModComboBox.getSelectedIndex();
            DefaultValues.setChargeModIndex(chargeModIndex);
            chargeValue = Double.parseDouble(charge.getText());
            xValue = Double.parseDouble(xPosition.getText());
            yValue = Double.parseDouble(yPosition.getText());
            chargesToCalc[okButtonPushes] = new PointCharge(chargeValue, xValue, yValue);
            charge.setText("0");
            xPosition.setText("0");
            yPosition.setText("0");
            okButtonPushes++;
            chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes));
            if (okButtonPushes == numberOfCharges) {
                confirm = JOptionPane.showConfirmDialog(null,
                        "You have entered " + okButtonPushes
                                + " charges. Press OK to confirm. \nPress Cancel to re-enter the charges",
                        null, JOptionPane.OK_CANCEL_OPTION);
                if (confirm == JOptionPane.OK_OPTION) {
                    DefaultValues.setCurrentPointCharges(chargesToCalc);
                    ElectroStaticUIContainer.removeGraphFromdisplayPanel();
                    theCalculator = new CalculatorPanel();
                    calcVec = new VectorCalculator(mapper);
                    volts = new VoltageAtPoint(mapper.getFieldPoints());
                    manGraph = new ManualPolygons(mapper);
                    chart = manGraph.delaunayBuild();
                    drawVecs = new DrawElectricFieldLines(mapper);
                    ElectroStaticUIContainer.add3DGraphToDisplayPanel(chart);
                    ElectroStaticUIContainer.addVectorGraphToDisplayPanel(drawVecs.getChart());
                    setVectorChartToSave();
                    setChart3dToSave();
                    rotateIt = new ChartMouseController(chart);
                    okButtonPushes = 0;
                    chargeDataFrame.removeAll();
                    chargeDataFrame.dispose();
                } else if (confirm == JOptionPane.CANCEL_OPTION)
                    okButtonPushes = 0;
            }

        }
        //while(okButtonPushes < numberOfCharges);

        //}
    });
}

From source file:net.sf.jabref.gui.exporter.SaveDatabaseAction.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;//from  ww w .  ja v a 2 s .c  o m
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(FileSaveSession::new);
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(),
                    panel.getSelectedEntries(), prefs);
        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.getMainTable().findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.getMainTable().setRowSelectionInterval(row, row);
            panel.getMainTable().scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file.toPath());
            panel.getBibDatabaseContext().getMetaData().setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:com.projity.dialog.AbstractDialog.java

public boolean doModal() {
    pack();//from ww w .  j a va 2s . co m
    setLocationRelativeTo(getParent());// to center on parent
    setVisible(true);
    return (getDialogResult() != JOptionPane.CANCEL_OPTION);
}

From source file:com.projity.dialog.AbstractDialog.java

public int execute(Closure setter, Closure getter) {
    pack();/*from  w w  w.  j a  v  a  2  s.c o m*/
    setter.execute(getBean());
    bind(true);
    setLocationRelativeTo(null);// to center on screen
    setVisible(true);
    if (getDialogResult() != JOptionPane.CANCEL_OPTION) {
        // bind(false); //already done in onOk
        if (getter != null)
            getter.execute(getBean());
    }
    return getDialogResult();
}

From source file:be.agiv.security.demo.Main.java

private void secConvIssueToken() {
    GridBagLayout gridBagLayout = new GridBagLayout();
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    JPanel contentPanel = new JPanel(gridBagLayout);

    JLabel urlLabel = new JLabel("URL:");
    gridBagConstraints.gridx = 0;/*from  ww w . j a  va2  s.  c o  m*/
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.ipadx = 5;
    gridBagLayout.setConstraints(urlLabel, gridBagConstraints);
    contentPanel.add(urlLabel);

    JTextField urlTextField = new JTextField(ClaimsAwareServiceFactory.SERVICE_SC_LOCATION, 60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(urlTextField, gridBagConstraints);
    contentPanel.add(urlTextField);

    JLabel warningLabel = new JLabel(
            "This operation can fail if the web service does not support WS-SecurityConversation.");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(warningLabel, gridBagConstraints);
    contentPanel.add(warningLabel);

    int result = JOptionPane.showConfirmDialog(this, contentPanel, "Secure Conversation Issue Token",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.CANCEL_OPTION) {
        return;
    }

    String location = urlTextField.getText();

    SecureConversationClient secConvClient = new SecureConversationClient(location);
    try {
        this.secConvSecurityToken = secConvClient.getSecureConversationToken(this.rStsSecurityToken);
        this.secConvViewMenuItem.setEnabled(true);
        this.secConvCancelMenuItem.setEnabled(true);
        secConvViewToken();
    } catch (Exception e) {
        showException(e);
    }
}