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

public static String showInputDialog(Component parentComponent, Object message) throws HeadlessException 

Source Link

Document

Shows a question-message dialog requesting input from the user parented to parentComponent.

Usage

From source file:net.sf.jabref.importer.fetcher.DOAJFetcher.java

@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    shouldContinue = true;//from w  w w  . jav a2 s  .com
    try {
        status.setStatus(Localization.lang("Searching..."));
        HttpResponse<JsonNode> jsonResponse;
        jsonResponse = Unirest.get(SEARCH_URL + query + "?pageSize=1").header("accept", "application/json")
                .asJson();
        JSONObject jo = jsonResponse.getBody().getObject();
        int hits = jo.getInt("total");
        int numberToFetch = 0;
        if (hits > 0) {
            if (hits > MAX_PER_PAGE) {
                while (true) {
                    String strCount = JOptionPane.showInputDialog(
                            Localization.lang("References found") + ": " + hits + "  "
                                    + Localization.lang("Number of references to fetch?"),
                            Integer.toString(hits));

                    if (strCount == null) {
                        status.setStatus(Localization.lang("%0 import canceled", "DOAJ"));
                        return false;
                    }

                    try {
                        numberToFetch = Integer.parseInt(strCount.trim());
                        break;
                    } catch (NumberFormatException ex) {
                        status.showMessage(Localization.lang("Please enter a valid number"));
                    }
                }
            } else {
                numberToFetch = hits;
            }

            int fetched = 0; // Keep track of number of items fetched for the progress bar
            for (int page = 1; ((page - 1) * MAX_PER_PAGE) <= numberToFetch; page++) {
                if (!shouldContinue) {
                    break;
                }

                int noToFetch = Math.min(MAX_PER_PAGE, numberToFetch - ((page - 1) * MAX_PER_PAGE));
                jsonResponse = Unirest.get(SEARCH_URL + query + "?page=" + page + "&pageSize=" + noToFetch)
                        .header("accept", "application/json").asJson();
                jo = jsonResponse.getBody().getObject();
                if (jo.has("results")) {
                    JSONArray results = jo.getJSONArray("results");
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject bibJsonEntry = results.getJSONObject(i).getJSONObject("bibjson");
                        BibEntry entry = jsonConverter.parseBibJSONtoBibtex(bibJsonEntry);
                        inspector.addEntry(entry);
                        fetched++;
                        inspector.setProgress(fetched, numberToFetch);
                    }
                }
            }
            return true;
        } else {
            status.showMessage(Localization.lang("No entries found for the search string '%0'", query),
                    Localization.lang("Search %0", "DOAJ"), JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
    } catch (UnirestException e) {
        LOGGER.warn("Problem searching DOAJ", e);
        status.setStatus(Localization.lang("%0 import canceled", "DOAJ"));
        return false;
    }

}

From source file:net.sf.jabref.importer.fetcher.SpringerFetcher.java

@Override
public boolean processQuery(String query, ImportInspector inspector, OutputPrinter status) {
    shouldContinue = true;// w  w w.ja  v a 2s .c o  m
    try {
        status.setStatus(Localization.lang("Searching..."));
        HttpResponse<JsonNode> jsonResponse;
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        jsonResponse = Unirest.get(API_URL + encodedQuery + "&api_key=" + API_KEY + "&p=1")
                .header("accept", "application/json").asJson();
        JSONObject jo = jsonResponse.getBody().getObject();
        int hits = jo.getJSONArray("result").getJSONObject(0).getInt("total");
        int numberToFetch = 0;
        if (hits > 0) {
            if (hits > MAX_PER_PAGE) {
                while (true) {
                    String strCount = JOptionPane.showInputDialog(
                            Localization.lang("References found") + ": " + hits + "  "
                                    + Localization.lang("Number of references to fetch?"),
                            Integer.toString(hits));

                    if (strCount == null) {
                        status.setStatus(Localization.lang("%0 import canceled", getTitle()));
                        return false;
                    }

                    try {
                        numberToFetch = Integer.parseInt(strCount.trim());
                        break;
                    } catch (NumberFormatException ex) {
                        status.showMessage(Localization.lang("Please enter a valid number"));
                    }
                }
            } else {
                numberToFetch = hits;
            }

            int fetched = 0; // Keep track of number of items fetched for the progress bar
            for (int startItem = 1; startItem <= numberToFetch; startItem += MAX_PER_PAGE) {
                if (!shouldContinue) {
                    break;
                }

                int noToFetch = Math.min(MAX_PER_PAGE, (numberToFetch - startItem) + 1);
                jsonResponse = Unirest.get(
                        API_URL + encodedQuery + "&api_key=" + API_KEY + "&p=" + noToFetch + "&s=" + startItem)
                        .header("accept", "application/json").asJson();
                jo = jsonResponse.getBody().getObject();
                if (jo.has("records")) {
                    JSONArray results = jo.getJSONArray("records");
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject springerJsonEntry = results.getJSONObject(i);
                        BibEntry entry = JSONEntryParser.parseSpringerJSONtoBibtex(springerJsonEntry);
                        inspector.addEntry(entry);
                        fetched++;
                        inspector.setProgress(fetched, numberToFetch);
                    }
                }
            }
            return true;
        } else {
            status.showMessage(Localization.lang("No entries found for the search string '%0'", encodedQuery),
                    Localization.lang("Search %0", getTitle()), JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
    } catch (UnirestException e) {
        LOGGER.warn("Problem searching Springer", e);
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Cannot encode query", e);
    }
    return false;

}

From source file:com.qspin.qtaste.testapi.impl.generic.UtilityImpl.java

@Override
public String getUserStringValue(final String message, final Object defaultValue) throws QTasteException {
    final StringBuilder valueBuilder = new StringBuilder();
    try {/* www  . j  av  a  2s  .  co m*/
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                String value = JOptionPane.showInputDialog(message, defaultValue);
                valueBuilder.append(value);
            }
        });
    } catch (Exception e) {
        throw new QTasteException("Error while showing user input dialog", e);
    }
    return valueBuilder.toString();
}

From source file:hr.fer.zemris.vhdllab.platform.ui.command.DevFloodWithCompliationRequestsCommand.java

private void floodWithCompilationRequests(final Integer fileId, final String name) {
    String input = JOptionPane.showInputDialog("How many?", "30");
    int floodCount = Integer.parseInt(input);

    final List<String> results = Collections.synchronizedList(new ArrayList<String>(floodCount));
    final CyclicBarrier barrier = new CyclicBarrier(floodCount);
    List<Thread> threads = new ArrayList<Thread>(floodCount);
    long start = System.currentTimeMillis();
    for (int i = 0; i < floodCount; i++) {
        Thread thread = new Thread(new Runnable() {
            @SuppressWarnings("synthetic-access")
            @Override//  w w  w .ja v a 2 s  .  c o m
            public void run() {
                try {
                    barrier.await();
                } catch (Exception e) {
                    throw new UnhandledException(e);
                }
                logger.info("sending at: " + System.currentTimeMillis());
                List<CompilationMessage> messages;
                try {
                    messages = simulator.compile(fileId);
                } catch (SimulatorTimeoutException e) {
                    String message = localizationSource.getMessage("simulator.compile.timout",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                } catch (NoAvailableProcessException e) {
                    String message = localizationSource.getMessage("simulator.compile.no.processes",
                            new Object[] { name });
                    messages = Collections.singletonList(new CompilationMessage(message));
                }

                if (messages.isEmpty()) {
                    results.add("Successful");
                } else {
                    results.add(messages.get(0).getText());
                }
            }
        });
        thread.start();
        threads.add(thread);
    }

    logger.info("waiting for threads to complete...");
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            throw new UnhandledException(e);
        }
    }
    long end = System.currentTimeMillis();
    logger.info("ended in " + (end - start) + " ms");
    showResults(results);
}

From source file:feedsplugin.FeedsSettingsTab.java

public JPanel createSettingsPanel() {
    final EnhancedPanelBuilder panelBuilder = new EnhancedPanelBuilder(
            FormFactory.RELATED_GAP_COLSPEC.encode() + ", fill:default:grow");
    final CellConstraints cc = new CellConstraints();

    mListModel = new DefaultListModel();
    for (String feed : mSettings.getFeeds()) {
        mListModel.addElement(feed);/*from   w w  w . j  a  v a2 s.  c om*/
    }
    mFeeds = new JList(mListModel);
    mFeeds.setSelectedIndex(0);
    mFeeds.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    mFeeds.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent e) {
            listSelectionChanged();
        }
    });

    panelBuilder.addGrowingRow();
    panelBuilder.add(new JScrollPane(mFeeds),
            cc.xyw(2, panelBuilder.getRow(), panelBuilder.getColumnCount() - 1));

    mAdd = new JButton(mLocalizer.msg("add", "Add feed"));
    mAdd.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
            String genre = JOptionPane.showInputDialog(mLocalizer.msg("addMessage", "Add feed URL"), "");
            if (genre != null) {
                genre = genre.trim();
                if (genre.length() > 0) {
                    mListModel.addElement(genre);
                }
            }
        }
    });

    mRemove = new JButton(mLocalizer.msg("remove", "Remove feed"));
    mRemove.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
            final int index = mFeeds.getSelectedIndex();
            if (index >= 0) {
                mListModel.remove(index);
            }
        }
    });

    panelBuilder.addRow();
    ButtonBarBuilder2 buttonBar = new ButtonBarBuilder2();
    buttonBar.addButton(new JButton[] { mAdd, mRemove });
    panelBuilder.add(buttonBar.getPanel(), cc.xyw(2, panelBuilder.getRow(), panelBuilder.getColumnCount() - 1));

    mFeeds.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent e) {
            mRemove.setEnabled(mFeeds.getSelectedIndex() >= 0);
        }
    });

    panelBuilder.addParagraph(mLocalizer.msg("moreFeeds", "Get more feeds"));
    panelBuilder.addRow();
    JEditorPane help = UiUtilities.createHtmlHelpTextArea(mLocalizer.msg("help",
            "You can find more news feeds on the <a href=\"{0}\">plugin help page</a>. If you know more interesting feeds, feel free to add them on that page.",
            StringUtils.replace(PluginInfo.getHelpUrl(FeedsPlugin.getInstance().getId()), "&", "&amp;")));
    panelBuilder.add(help, cc.xyw(2, panelBuilder.getRow(), panelBuilder.getColumnCount() - 1));

    // force update of enabled states
    listSelectionChanged();

    return panelBuilder.getPanel();
}

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

/**
 * Start a download./* w  w w.  j  a  va  2 s  .  co m*/
 *
 * @param callback The object to which the filename should be reported when download
 *                 is complete.
 */
public void download(final DownloadCallback callback) throws IOException {
    dontShowDialog = false;
    final String res = JOptionPane.showInputDialog(frame, Localization.lang("Enter URL to download"));

    if ((res == null) || res.trim().isEmpty()) {
        return;
    }

    URL url;
    try {
        url = new URL(res);
    } catch (MalformedURLException ex1) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Invalid URL"),
                Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
        return;
    }

    download(url, callback);
}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

@Override
protected void startup() {
    statusbar = new LockingStatusbar(this, getMainFrame(), settings);
    statusbar.addLockingListener(lockingListener);
    startTime = System.currentTimeMillis();
    log.info("Application started @[" + startTime + "]");
    player.addListener(playerListener);/*  ww w  . j  a  v a 2  s.c o m*/

    playerModel.addPlaylistListener(playListListener);

    addExitListener(new ExitListener() {

        @Override
        public boolean canExit(EventObject eo) {
            if (settings.isPasswordValid(null) || unlocked) {
                return true;
            } else {
                final String showInputDialog = JOptionPane.showInputDialog(getMainFrame(),
                        getText("exit.requestPin.label"));
                return showInputDialog != null && settings.isPasswordValid(DigestUtils.md5Hex(showInputDialog));
            }
        }

        @Override
        public void willExit(EventObject eo) {
            playerModel.exportXML(PathUtil.getLibraryFile());
            settings.backup(PathUtil.getSettingsFile());
            playerModel.logUserFavorites();
            log.info("Application stopped @[" + System.currentTimeMillis() + "] running for ["
                    + (System.currentTimeMillis() - startTime) / 1000 + "]seconds");
        }
    });

    FrameView mainView = getMainView();
    mainView.setComponent(createMainComponent());
    mainView.setStatusBar(statusbar);
    show(mainView);
}

From source file:edu.ku.brc.specify.rstools.GoogleEarthExporter.java

public void processRecordSet(final RecordSetIFace recordSet, final Properties reqParams) {
    useKMZ = AppPreferences.getLocalPrefs().getBoolean("USE_GE_KMZ", false);

    String description = JOptionPane.showInputDialog(getTopWindow(), getResourceString("GE_ENTER_DESC"));

    log.info("Exporting RecordSet");
    int dataTableId = recordSet.getDbTableId();

    if (dataTableId == CollectingEvent.getClassTableId()) {
        exportDataObjects(description, RecordSetLoader.loadRecordSet(recordSet), useKMZ, getPlacemarkIcon());

    } else if (dataTableId == CollectionObject.getClassTableId()) {
        exportCollectionObjectRecordSet(description, recordSet);

    } else if (dataTableId == Locality.getClassTableId()) {
        exportLocalityRecordSet(description, recordSet);

    } else {//from   ww w . ja  va 2s .c  om
        throw new RuntimeException(
                "Only Collection Objects, Colelcting Events and Localities are supported for GoogleEarth export."); // I18N
    }
}

From source file:io.github.jeddict.relation.mapper.widget.table.BaseTableWidget.java

@Override
protected List<JMenuItem> getPopupMenuItemList() {
    List<JMenuItem> menuList = super.getPopupMenuItemList();
    JMenuItem menuItem = new JMenuItem("Create Secondary Table");
    menuItem.addActionListener((ActionEvent e) -> {
        Entity entity = this.getBaseElementSpec().getEntity();
        String secondaryTableName = JOptionPane.showInputDialog(
                (Component) BaseTableWidget.this.getModelerScene().getModelerPanelTopComponent(),
                "Please enter secondary table name");
        if (entity.getTable(secondaryTableName) == null) { //check from complete table list
            SecondaryTable secondaryTable = new SecondaryTable();
            secondaryTable.setName(secondaryTableName);
            entity.addSecondaryTable(secondaryTable);
            ModelerFile parentFile = BaseTableWidget.this.getModelerScene().getModelerFile().getParentFile();
            DBUtil.openDBModeler(parentFile);
            JeddictLogger.recordDBAction("Create Secondary Table");
        } else {//from   w  ww .  j a va  2  s .c  o  m
            JOptionPane.showMessageDialog(
                    (Component) BaseTableWidget.this.getModelerScene().getModelerPanelTopComponent(),
                    "Table already exist");
        }
    });
    menuList.add(0, menuItem);
    return menuList;
}

From source file:org.jtheque.ui.impl.UIUtilsImpl.java

@Override
public String askText(String text) {
    Window parent = null;//ww  w  . j  a va2s .co m

    if (SimplePropertiesCache.get(MAIN_VIEW_CACHE, Component.class) != null) {
        parent = (Window) SimplePropertiesCache.get(MAIN_VIEW_CACHE, Component.class);
    }

    return JOptionPane.showInputDialog(parent, text);
}