Example usage for javax.swing JDialog dispose

List of usage examples for javax.swing JDialog dispose

Introduction

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

Prototype

public void dispose() 

Source Link

Document

Releases all of the native screen resources used by this Window , its subcomponents, and all of its owned children.

Usage

From source file:org.datavyu.views.DataControllerV.java

/**
 * Remove the specified viewer from the controller.
 *
 * @param id/* www.ja va 2s  .  c om*/
 *            The identifier of the viewer to shutdown.
 */
public void shutdown(final Identifier id) {
    DataViewer viewer = null;

    for (DataViewer v : viewers) {

        if (v.getIdentifier().equals(id)) {
            viewer = v;

            break;
        }
    }

    if ((viewer == null) || !shouldRemove()) {
        return;
    }

    viewers.remove(viewer);

    viewer.stop();
    viewer.clearDataFeed();

    JDialog viewDialog = viewer.getParentJDialog();

    if (viewDialog != null) {
        viewDialog.dispose();
    }

    // BugzID:2000
    viewer.removeViewerStateListener(
            mixerController.getTracksEditorController().getViewerStateListener(viewer.getIdentifier()));

    // Recalculate the maximum playback duration.
    updateMaxViewerDuration();

    // Remove the data viewer from the tracks panel.
    mixerController.deregisterTrack(viewer.getIdentifier());

    // Data viewer removed, mark project as changed.
    Datavyu.getProjectController().projectChanged();

}

From source file:org.deegree.tools.rendering.viewer.File3dImporter.java

public static List<WorldRenderableObject> open(Frame parent, String fileName) {

    if (fileName == null || "".equals(fileName.trim())) {
        throw new InvalidParameterException("the file name may not be null or empty");
    }/*w  ww .  j av a  2 s.c  o m*/
    fileName = fileName.trim();

    CityGMLImporter openFile2;
    XMLInputFactory fac = XMLInputFactory.newInstance();
    InputStream in = null;
    try {
        XMLStreamReader reader = fac.createXMLStreamReader(in = new FileInputStream(fileName));
        reader.next();
        String ns = "http://www.opengis.net/citygml/1.0";
        openFile2 = new CityGMLImporter(null, null, null, reader.getNamespaceURI().equals(ns));
    } catch (Throwable t) {
        openFile2 = new CityGMLImporter(null, null, null, false);
    } finally {
        IOUtils.closeQuietly(in);
    }

    final CityGMLImporter openFile = openFile2;

    final JDialog dialog = new JDialog(parent, "Loading", true);

    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(
            new JLabel("<HTML>Loading file:<br>" + fileName + "<br>Please wait!</HTML>", SwingConstants.CENTER),
            BorderLayout.NORTH);
    final JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setIndeterminate(false);
    dialog.getContentPane().add(progressBar, BorderLayout.CENTER);

    dialog.pack();
    dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    dialog.setResizable(false);
    dialog.setLocationRelativeTo(parent);

    final Thread openThread = new Thread() {
        /**
         * Opens the file in a separate thread.
         */
        @Override
        public void run() {
            // openFile.openFile( progressBar );
            if (dialog.isDisplayable()) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        }
    };
    openThread.start();

    dialog.setVisible(true);
    List<WorldRenderableObject> result = null;
    try {
        result = openFile.importFromFile(fileName, 6, 2);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    gm = openFile.getQmList();

    //
    // if ( result != null ) {
    // openGLEventListener.addDataObjectToScene( result );
    // File f = new File( fileName );
    // setTitle( WIN_TITLE + f.getName() );
    // } else {
    // showExceptionDialog( "The file: " + fileName
    // + " could not be read,\nSee error log for detailed information." );
    // }
    return result;
}

From source file:org.drugis.addis.gui.WelcomeDialog.java

private void showExampleInfo(String helpText) {
    final JDialog dialog = new JDialog(this);
    dialog.setLocationByPlatform(true);//from  ww w .  j av  a  2  s.  c o m
    dialog.setPreferredSize(new Dimension(500, 250));

    JComponent helpPane = TextComponentFactory.createTextPane(helpText, true);

    JButton closeButton = new JButton("Close");
    closeButton.setMnemonic('c');
    closeButton.addActionListener(new AbstractAction() {
        public void actionPerformed(ActionEvent arg0) {
            dialog.dispose();
        }
    });

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(helpPane, BorderLayout.CENTER);
    panel.add(closeButton, BorderLayout.SOUTH);

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

From source file:org.executequery.gui.browser.SSHTunnelConnectionPanel.java

public boolean canConnect() {

    if (useSshCheckbox.isSelected()) {

        if (!hasValue(userNameField)) {

            GUIUtilities//from   w  w w  .j a  va 2  s . c om
                    .displayErrorMessage("You have selected SSH Tunnel but have not provided an SSH user name");
            return false;
        }

        if (!hasValue(portField)) {

            GUIUtilities.displayErrorMessage("You have selected SSH Tunnel but have not provided an SSH port");
            return false;
        }

        if (!hasValue(passwordField)) {

            final JPasswordField field = WidgetFactory.createPasswordField();

            JOptionPane optionPane = new JOptionPane(field, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION);
            JDialog dialog = optionPane.createDialog("Enter SSH password");

            dialog.addWindowFocusListener(new WindowAdapter() {
                @Override
                public void windowGainedFocus(WindowEvent e) {
                    field.requestFocusInWindow();
                }
            });

            dialog.pack();
            dialog.setLocation(GUIUtilities.getLocationForDialog(dialog.getSize()));
            dialog.setVisible(true);
            dialog.dispose();

            int result = Integer.parseInt(optionPane.getValue().toString());
            if (result == JOptionPane.OK_OPTION) {

                String password = MiscUtils.charsToString(field.getPassword());
                if (StringUtils.isNotBlank(password)) {

                    passwordField.setText(password);
                    return true;

                } else {

                    GUIUtilities.displayErrorMessage(
                            "You have selected SSH Tunnel but have not provided an SSH password");

                    // send back here and force them to select cancel if they want to bail

                    return canConnect();
                }

            }
            return false;
        }

    }

    return true;
}

From source file:org.gofleet.module.routing.RoutingMap.java

private void newPlan(LatLon from) {
    JDialog d = new JDialog(basicWindow.getFrame(), "Generating New Plan");
    try {//from  w  w  w  .j  a v  a2  s  .c  o  m
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new RoutingFilter());
        fc.setAcceptAllFileFilterUsed(true);
        int returnVal = fc.showOpenDialog(basicWindow.getFrame());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            log.debug("Opening: " + file.getName());

            JProgressBar progressBar = new JProgressBar(0, getNumberLines(file) * 2);
            progressBar.setValue(0);
            progressBar.setPreferredSize(new Dimension(150, 50));
            progressBar.setStringPainted(true);

            d.add(progressBar);
            d.pack();
            d.setVisible(true);

            TSPPlan[] param = processFile(file, progressBar);

            Map<String, String> values = getValues(from);

            double[] origin = new double[2];
            origin[0] = new Double(values.get("origin_x"));
            origin[1] = new Double(values.get("origin_y"));

            TSPPlan[] res = calculateRouteOnWS(new Integer(values.get("maxDistance")),
                    new Integer(values.get("maxTime")), origin, new Integer(values.get("startTime")), param,
                    new Integer(values.get("timeSpentOnStop")));

            progressBar.setValue(progressBar.getMaximum() - res.length);

            processTSPPlan(res, progressBar);

        } else {
            log.trace("Open command cancelled by user.");
        }
    } catch (Throwable t) {
        log.error("Error computing new plan", t);
        JOptionPane.showMessageDialog(basicWindow.getFrame(),
                "<html><p>" + i18n.getString("Main.Error") + ":</p><p>" + t.toString() + "</p><html>",
                i18n.getString("Main.Error"), JOptionPane.ERROR_MESSAGE);
    } finally {
        d.setVisible(false);
        d.dispose();
    }

}

From source file:org.gofleet.module.routing.RoutingMap.java

private Map<String, String> getValues(LatLon from) {
    final Map<String, String> mapa = new HashMap<String, String>();
    final JDialog frame = new JDialog(basicWindow.getFrame(), "Configuration");
    JPanel panel = new JPanel(new GridLayout(0, 2));
    int width = 10;

    final JTextField maxDistance = new JTextField(width);
    maxDistance.setText("10");
    final JTextField maxTime = new JTextField(width);
    maxTime.setText("8");
    final JTextField origin_x = new JTextField(width / 2);
    origin_x.setText((new Double(from.getX())).toString());
    final JTextField origin_y = new JTextField(width / 2);
    origin_y.setText((new Double(from.getY())).toString());
    final JTextField startTime = new JTextField(width);
    startTime.setText("7");
    final JTextField timeSpentOnStop = new JTextField(width);
    timeSpentOnStop.setText("1");
    JLabel lmaxDistance = new JLabel("Maximum Distance (km)");
    lmaxDistance.setLabelFor(maxDistance);
    JLabel lmaxTime = new JLabel("Maximum Time (hours)");
    lmaxTime.setLabelFor(maxTime);/*from w  w w.j  a  v a  2s  .  c om*/
    JLabel lorigin = new JLabel("Point of Origin");
    lorigin.setLabelFor(origin_x);
    JLabel lstartTime = new JLabel("Start Time of Plan (0-24)");
    lstartTime.setLabelFor(startTime);
    JLabel ltimeSpentOnStop = new JLabel("Time Spent on Stop (hours)");
    ltimeSpentOnStop.setLabelFor(timeSpentOnStop);

    JButton close = new JButton("OK");
    close.addActionListener(new AbstractAction() {

        private static final long serialVersionUID = -8912729211256933464L;

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                mapa.put("maxDistance", maxDistance.getText());
                mapa.put("maxTime", maxTime.getText());
                mapa.put("origin_x", origin_x.getText());
                mapa.put("origin_y", origin_y.getText());
                mapa.put("startTime", startTime.getText());
                mapa.put("timeSpentOnStop", timeSpentOnStop.getText());
                frame.dispose();
            } catch (Throwable t) {
                log.error("Error configuring New Route Plan" + t);
                JOptionPane.showMessageDialog(RoutingMap.this, "Some values are wrong. Check them again.");
            }
        }
    });

    panel.add(lmaxDistance);
    panel.add(maxDistance);
    panel.add(lmaxTime);
    panel.add(maxTime);
    panel.add(lorigin);
    JPanel panel_origin = new JPanel();
    panel_origin.add(origin_x);
    panel_origin.add(origin_y);
    panel.add(panel_origin);
    panel.add(lstartTime);
    panel.add(startTime);
    panel.add(ltimeSpentOnStop);
    panel.add(timeSpentOnStop);
    panel.add(close);
    frame.add(panel, BorderLayout.CENTER);
    frame.pack();
    frame.setModalityType(ModalityType.APPLICATION_MODAL);
    frame.setVisible(true);

    return mapa;
}

From source file:org.javaswift.cloudie.CloudiePanel.java

public void onLogin() {
    final JDialog loginDialog = new JDialog(owner, "Login");
    final LoginPanel loginPanel = new LoginPanel(new LoginCallback() {
        @Override/*from w  ww .  j  a va 2 s  . c  o m*/
        public void doLogin(AccountConfig accountConfig) {
            CloudieCallback cb = GuiTreadingUtils.guiThreadSafe(CloudieCallback.class,
                    new CloudieCallbackWrapper(callback) {
                        @Override
                        public void onLoginSuccess() {
                            loginDialog.setVisible(false);
                            super.onLoginSuccess();
                        }

                        @Override
                        public void onError(CommandException ex) {
                            JOptionPane.showMessageDialog(loginDialog, "Login Failed\n" + ex.toString(),
                                    "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    });
            ops.login(accountConfig, cb);
        }
    }, credentialsStore);
    try {
        loginPanel.setOwner(loginDialog);
        loginDialog.getContentPane().add(loginPanel);
        loginDialog.setModal(true);
        loginDialog.setSize(480, 340);
        loginDialog.setResizable(false);
        loginDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        center(loginDialog);
        loginDialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                loginPanel.onCancel();
            }

            @Override
            public void windowOpened(WindowEvent e) {
                loginPanel.onShow();
            }
        });
        loginDialog.setVisible(true);
    } finally {
        loginDialog.dispose();
    }
}

From source file:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java

/**
 * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog.
 *///from   w  ww.  ja  v  a2 s  .  com
@Override
public void actionPerformed(ActionEvent e) {
    if (abort()) {
        return;
    }

    //        SendAssetConfirmDialog sendAssetConfirmDialog = null;
    AssetValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);
        String sendMessage = null;
        boolean canSendMessage = false;

        final int assetId = dataProvider.getAssetId();
        String assetAmount = dataProvider.getAssetAmount();
        boolean isSenderPays = dataProvider.isSenderPays();

        /* Is there a payment charge?  If yes, the asset amount will change */
        CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId);
        CoinSparkGenesis genesis = asset.getGenesis();
        BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount);
        // Was there any rounding, which the user did not see because they clicked on send first,
        // without losing focus to any other widget which corrects field?
        String typedAmount = dataProvider.getAssetAmountText();
        BigDecimal bd1 = new BigDecimal(typedAmount);
        BigDecimal bd2 = new BigDecimal(assetAmount);
        bd1 = bd1.stripTrailingZeros();
        bd2 = bd2.stripTrailingZeros();
        if (bd1.equals(bd2) == false) {
            String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE);
            String s = "The smallest transactable unit is " + displayUnit
                    + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again.";
            JOptionPane.showMessageDialog(mainFrame, s);
            return;
        }
        // End rounding check/warning

        long desiredRawUnits = assetAmountRawUnits.longValue();
        short chargeBasisPoints = genesis.getChargeBasisPoints();
        long rawFlatChargeAmount = genesis.getChargeFlat();
        boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0);
        if (chargeExists) {
            if (isSenderPays) {
                long x = genesis.calcGross(desiredRawUnits);
                assetAmountRawUnits = new BigInteger(String.valueOf(x));
            } else {
                // We don't have to do anything if recipient pays, just send gross amount.
                // calcNet() returns what the recipient will receive, but it's not what we send.
                //          long x = genesis.calcNet(desiredRawUnits);
                //          assetAmountRawUnits = new BigInteger(String.valueOf(x));          
            }
        }

        // Todo: Allow invalid assets to be sent even if spendable balance is 0
        //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) 
        final AssetValidator validator = new AssetValidator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) {
            /* CoinSpark START */
            CoinSparkPaymentRef paymentRef = null;

            // We have already validated that the coinspark address and underlying bitcoin are good
            // and that the transfer flag is set on the coinspark address.  We just want the actual
            // underlying bitcoin address to send assets to, which is used to create SendRequest object.
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            sendAddress = btcAddress;

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
                log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
            }

            // Messages - can send message and BTC to CoinSpark address, without any assets.
            sendMessage = dataProvider.getMessage();
            canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0;
            /* CoinSpark END */

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));

            //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) {
            //BigInteger assetAmountRawUnits = new BigInteger(assetAmount);
            BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

            final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId,
                    assetAmountRawUnits, 1);
            sendRequest.ensureMinRequiredFee = true;
            sendRequest.fee = BigInteger.ZERO;
            sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

            // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

            // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
            if (paymentRef != null && paymentRef.getRef() != 0) {
                sendRequest.setPaymentRef(paymentRef);
            }

            // Send a message if the address will take it and message is not empty
            boolean willSendMessage = false;
            if (canSendMessage) {
                boolean isEmptyMessage = false;
                if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) {
                    isEmptyMessage = true;
                }
                if (!isEmptyMessage) {
                    willSendMessage = true;
                    //int numParts = 1;
                    CoinSparkMessagePart[] parts = {
                            CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) };
                    String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController);
                    sendRequest.setMessage(parts, serverURLs);

                    log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
                    log.debug(">>>> parts[0] = " + parts[0]);
                    log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
                    log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
                    log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"));
                    //String message = "Hello, the time is now..." + DateTime.now().toString();
                    //      parts[2].fileName = imagePath;
                    //      parts[2].mimeType = "image/png";
                    //      byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
                    //      parts[2].content = imageBytes;

                }
            }

            //
            // When sending a message, show a modal dialog.
            // CompleteTX now occurs in background thread so UI does not block
            // when "Send" is clicked with widget updates frozen.
            //

            // Show dialog with indeterminate progress bar
            final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame,
                    "SparkBit", "Contacting message delivery servers...");
            // Dialog is made visible after futures have been set up

            ListeningExecutorService service = MoreExecutors
                    .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10));
            ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    try {
                        // Complete it (which works out the fee) but do not sign it yet.
                        log.debug("Just about to complete the tx (and calculate the fee)...");
                        bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                        log.debug("The fee after completing the transaction was " + sendRequest.fee);

                    } catch (Exception e) {
                        throw e;
                    }
                    return true;
                }
            });

            final BigInteger myAssetAmountRawUnits = assetAmountRawUnits;

            Futures.addCallback(future, new FutureCallback<Boolean>() {
                public void onSuccess(Boolean b) {

                    // There is enough money.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits,
                                    validator);
                            mySendAssetConfirmDialog.setVisible(true);
                        }
                    });

                }

                public void onFailure(Throwable thrown) {
                    final String failureReason = thrown.getMessage();
                    final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode;
                    final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException;
                    // There is not enough money.
                    // TODO setup validation parameters accordingly so that it displays ok.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            if (isCSException) {
                                JOptionPane
                                        .showMessageDialog(mainFrame,
                                                "SparkBit is unable to proceed with this transaction:\n\n"
                                                        + failureReason,
                                                "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                            } else if (isInsufficientMoney) {
                                // Try to show a human friendly message, need to pass the missing satoshis from failure reason.
                                try {
                                    String numberOnly = failureReason.replaceAll("[^0-9]", "");
                                    BigInteger needed = new BigInteger(numberOnly);
                                    JOptionPane.showMessageDialog(mainFrame,
                                            "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require "
                                                    + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.",
                                            "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                                } catch (NumberFormatException e) {
                                    AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true, validator);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {

                                AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true, validator);
                                myValidationErrorDialog.setVisible(true);
                            }
                        }
                    });
                }
            });

            // Show message server dialog only if we are going to send
            if (willSendMessage) {
                dialog.setVisible(true);
            }

            /*      
                            // Complete it (which works out the fee) but do not sign it yet.
                            log.debug("Just about to complete the tx (and calculate the fee)...");
                            boolean completedOk;
                            try {
            bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                              completedOk = true;
                              log.debug("The fee after completing the transaction was " + sendRequest.fee);
                            } catch (InsufficientMoneyException ime) {
                              completedOk = false;
                            }
                            if (completedOk) {
            // There is enough money.
                    
            sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator);
            sendAssetConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator);
            validationErrorDialog.setVisible(true);
                            }
            */

        } else {
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null,
                    false, validator);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount.");
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:org.multibit.viewsystem.swing.action.SendBitcoinConfirmAction.java

/**
 * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog.
 *//*from  w w w  . jav  a  2 s.  c o m*/
@Override
public void actionPerformed(ActionEvent e) {
    if (abort()) {
        return;
    }

    //        SendBitcoinConfirmDialog sendBitcoinConfirmDialog = null;
    ValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = dataProvider.getAmount();
        String sendMessage = null;
        boolean canSendMessage = false;

        /*CoinSpark START */
        CoinSparkPaymentRef paymentRef = null;

        /*
         If the address is a coinspark address, retrieve the bitcoin address and let the validator check it.
         The SendRequest object will use the bitcoin address, while the confirmation dialog will use
         whatever is displayed in the address text field i.e. coinspark address, if there is one.
         For reference, you can see what is in the textfield, which has been saved in prefs:
         String address = this.bitcoinController.getModel().getActiveWalletPreference(BitcoinModel.SEND_ADDRESS
         */
        if (sendAddress.startsWith("s")) {
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            if (btcAddress != null) {
                sendAddress = btcAddress; // the validator will check the btcAddress like normal.
            }

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
            }

            // Messages - can send message and BTC to CoinSpark address, without any assets.
            sendMessage = ((AssetFormDataProvider) dataProvider).getMessage();
            canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0;
        }
        /*CoinSpark END */

        Validator validator = new Validator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount)) {
            // The address and amount are valid.

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            final SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));
            //                SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),1);
            sendRequest.ensureMinRequiredFee = true;
            sendRequest.fee = BigInteger.ZERO;
            sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

            // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

            // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
            if (paymentRef != null && paymentRef.getRef() != 0) {
                sendRequest.setPaymentRef(paymentRef);
            }

            // Send a message if the address will take it and message is not empty
            boolean willSendMessage = false;
            if (canSendMessage) {
                boolean isEmptyMessage = false;
                if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) {
                    isEmptyMessage = true;
                }
                if (!isEmptyMessage) {
                    willSendMessage = true;
                    CoinSparkMessagePart[] parts = {
                            CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) };
                    String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController);
                    sendRequest.setMessage(parts, serverURLs);

                    log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
                    log.debug(">>>> parts[0] = " + parts[0]);
                    log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
                    log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
                    log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"));
                    //String message = "Hello, the time is now..." + DateTime.now().toString();
                    //      parts[2].fileName = imagePath;
                    //      parts[2].mimeType = "image/png";
                    //      byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
                    //      parts[2].content = imageBytes;

                }
            }

            //
            // When sending a message, show a modal dialog.
            // CompleteTX now occurs in background thread so UI does not block
            // when "Send" is clicked with widget updates frozen.
            //

            // Show dialog with indeterminate progress bar
            final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame,
                    "SparkBit", "Contacting message delivery servers...");
            // Dialog is made visible after futures have been set up

            ListeningExecutorService service = MoreExecutors
                    .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10));
            ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    try {
                        // Complete it (which works out the fee) but do not sign it yet.
                        log.debug("Just about to complete the tx (and calculate the fee)...");
                        bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                        log.debug("The fee after completing the transaction was " + sendRequest.fee);

                    } catch (Exception e) {
                        throw e;
                    }
                    return true;
                }
            });

            Futures.addCallback(future, new FutureCallback<Boolean>() {
                public void onSuccess(Boolean b) {

                    // There is enough money.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            SendBitcoinConfirmDialog mySendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest);
                            mySendBitcoinConfirmDialog.setVisible(true);
                        }
                    });

                }

                public void onFailure(Throwable thrown) {
                    final String failureReason = thrown.getMessage();
                    final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode;
                    final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException;
                    // There is not enough money.
                    // TODO setup validation parameters accordingly so that it displays ok.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            if (isCSException) {
                                JOptionPane
                                        .showMessageDialog(mainFrame,
                                                "SparkBit is unable to proceed with this transaction:\n\n"
                                                        + failureReason,
                                                "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                            } else if (isInsufficientMoney) {
                                // Try to show a human friendly message, need to pass the missing satoshis from failure reason.
                                try {
                                    String numberOnly = failureReason.replaceAll("[^0-9]", "");
                                    BigInteger needed = new BigInteger(numberOnly);
                                    JOptionPane.showMessageDialog(mainFrame,
                                            "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require "
                                                    + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.",
                                            "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                                } catch (NumberFormatException e) {
                                    ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {
                                ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true);
                                myValidationErrorDialog.setVisible(true);
                            }
                        }
                    });
                }
            });

            // Show message server dialog only if we are going to send
            if (willSendMessage) {
                dialog.setVisible(true);
            }

            /*      
                            // Complete it (which works out the fee) but do not sign it yet.
                            log.debug("Just about to complete the tx (and calculate the fee)...");
                            boolean completedOk;
                            try {
            bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                              completedOk = true;
                              log.debug("The fee after completing the transaction was " + sendRequest.fee);
                            } catch (InsufficientMoneyException ime) {
                              completedOk = false;
                            }
                            if (completedOk) {
            // There is enough money.
                    
            sendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(super.bitcoinController, mainFrame, sendRequest);
            sendBitcoinConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true);
            validationErrorDialog.setVisible(true);
                            }
               */

        } else {
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, null, false);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:org.notebook.gui.widget.GuiUtils.java

/**
 * Adds the dispose action with escape key.
 * //from w  w  w  .ja  v a 2  s. c  o m
 * @param dialog
 *            the dialog
 */
public static void addDisposeActionWithEscapeKey(final JDialog dialog) {
    //  Handle escape key to close the dialog

    KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
    Action disposeAction = new AbstractAction() {
        private static final long serialVersionUID = 0L;

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    };
    dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
    dialog.getRootPane().getActionMap().put("ESCAPE", disposeAction);
}