Example usage for javax.swing JOptionPane showInputDialog

List of usage examples for javax.swing JOptionPane showInputDialog

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:net.fabricmc.installer.installer.MultiMCInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress) throws Exception {
    File instancesDir = new File(mcDir, "instances");
    if (!instancesDir.exists()) {
        throw new FileNotFoundException(Translator.getString("install.multimc.notFound"));
    }/* ww  w. j  a v a 2s. c o m*/
    progress.updateProgress(Translator.getString("install.multimc.findInstances"), 10);
    String mcVer = version.split("-")[0];
    List<File> validInstances = new ArrayList<>();
    for (File instanceDir : instancesDir.listFiles()) {
        if (instanceDir.isDirectory()) {
            if (isValidInstance(instanceDir, mcVer)) {
                validInstances.add(instanceDir);
            }
        }
    }
    if (validInstances.isEmpty()) {
        throw new Exception(Translator.getString("install.multimc.noInstances").replace("[MCVER]", mcVer));
    }
    List<String> instanceNames = new ArrayList<>();
    for (File instance : validInstances) {
        instanceNames.add(instance.getName());
    }
    String instanceName = (String) JOptionPane.showInputDialog(null,
            Translator.getString("install.multimc.selectInstance"),
            Translator.getString("install.multimc.selectInstance"), JOptionPane.QUESTION_MESSAGE, null,
            instanceNames.toArray(), instanceNames.get(0));
    if (instanceName == null) {
        progress.updateProgress(Translator.getString("install.multimc.canceled"), 100);
        return;
    }
    progress.updateProgress(
            Translator.getString("install.multimc.installingInto").replace("[NAME]", instanceName), 25);
    File instnaceDir = null;
    for (File instance : validInstances) {
        if (instance.getName().equals(instanceName)) {
            instnaceDir = instance;
        }
    }
    if (instnaceDir == null) {
        throw new FileNotFoundException("Could not find " + instanceName);
    }
    File patchesDir = new File(instnaceDir, "patches");
    if (!patchesDir.exists()) {
        patchesDir.mkdir();
    }
    File fabricJar = new File(patchesDir, "Fabric-" + version + ".jar");
    if (!fabricJar.exists()) {
        progress.updateProgress(Translator.getString("install.client.downloadFabric"), 30);
        FileUtils.copyURLToFile(new URL("http://maven.modmuss50.me/net/fabricmc/fabric-base/" + version
                + "/fabric-base-" + version + ".jar"), fabricJar);
    }
    progress.updateProgress(Translator.getString("install.multimc.createJson"), 70);
    File fabricJson = new File(patchesDir, "fabric.json");
    if (fabricJson.exists()) {
        fabricJson.delete();
    }
    String json = readBaseJson();
    json = json.replaceAll("%VERSION%", version);

    ZipFile fabricZip = new ZipFile(fabricJar);
    ZipEntry dependenciesEntry = fabricZip.getEntry("dependencies.json");
    String fabricDeps = IOUtils.toString(fabricZip.getInputStream(dependenciesEntry), Charset.defaultCharset());
    json = json.replace("%DEPS%", stripDepsJson(fabricDeps.replace("\n", "")));
    FileUtils.writeStringToFile(fabricJson, json, Charset.defaultCharset());
    fabricZip.close();
    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:latexstudio.editor.remote.UploadToDropbox.java

@Override
public void actionPerformed(ActionEvent e) {
    DbxClient client = DbxUtil.getDbxClient();

    if (client == null) {
        return;/*w ww.j a v  a2s . com*/
    }

    String sourceFileName = ApplicationUtils.getTempSourceFile();
    File file = new File(sourceFileName);

    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file);
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    }

    String defaultFileName = etc.getCurrentFile() == null ? "welcome.tex" : etc.getCurrentFile().getName();
    String fileName = (String) JOptionPane.showInputDialog(null, "Please enter file name", "Upload file",
            JOptionPane.INFORMATION_MESSAGE, null, null, defaultFileName);
    if (fileName != null) {
        fileName = fileName.endsWith(TEX_EXTENSION) ? fileName : fileName.concat(TEX_EXTENSION);
        try {
            DbxEntry.File uploadedFile = client.uploadFile("/OpenLaTeXStudio/" + fileName, DbxWriteMode.add(),
                    file.length(), inputStream);
            JOptionPane.showMessageDialog(null,
                    "Successfuly uploaded file " + uploadedFile.name + " (" + uploadedFile.humanSize + ")",
                    "File uploaded to Dropbox", JOptionPane.INFORMATION_MESSAGE);
            revtc.close();
        } catch (DbxException ex) {
            DbxUtil.showDbxAccessDeniedPrompt();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

From source file:BeanContainer.java

  protected JMenuBar createMenuBar() {
  JMenuBar menuBar = new JMenuBar();
    /*from w ww .  java 2s  .  c om*/
  JMenu mFile = new JMenu("File");

  JMenuItem mItem = new JMenuItem("New...");
  ActionListener lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {  
      Thread newthread = new Thread() {
        public void run() {
          String result = (String)JOptionPane.showInputDialog(
            BeanContainer.this, 
            "Please enter class name to create a new bean", 
            "Input", JOptionPane.INFORMATION_MESSAGE, null, 
            null, m_className);
          repaint();
          if (result==null)
            return;
          try {
            m_className = result;
            Class cls = Class.forName(result);
            Object obj = cls.newInstance();
            if (obj instanceof Component) {
              m_activeBean = (Component)obj;
              m_activeBean.addFocusListener(
                BeanContainer.this);
              m_activeBean.requestFocus();
              getContentPane().add(m_activeBean);
            }
            validate();
          }
          catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
              BeanContainer.this, "Error: "+ex.toString(),
              "Warning", JOptionPane.WARNING_MESSAGE);
          }
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mItem = new JMenuItem("Load...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {  
      Thread newthread = new Thread() {
        public void run() {
          m_chooser.setCurrentDirectory(m_currentDir);
          m_chooser.setDialogTitle(
            "Please select file with serialized bean");
          int result = m_chooser.showOpenDialog(
            BeanContainer.this);
          repaint();
          if (result != JFileChooser.APPROVE_OPTION)
            return;
          m_currentDir = m_chooser.getCurrentDirectory();
          File fChoosen = m_chooser.getSelectedFile();
          try {
            FileInputStream fStream = 
              new FileInputStream(fChoosen);
            ObjectInput  stream  =  
              new ObjectInputStream(fStream);
            Object obj = stream.readObject();
            if (obj instanceof Component) {
              m_activeBean = (Component)obj;
              m_activeBean.addFocusListener(
                BeanContainer.this);
              m_activeBean.requestFocus();
              getContentPane().add(m_activeBean);
            }
            stream.close();
            fStream.close();
            validate();
          }
          catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
              BeanContainer.this, "Error: "+ex.toString(),
              "Warning", JOptionPane.WARNING_MESSAGE);
          }
          repaint();
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mItem = new JMenuItem("Save...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      Thread newthread = new Thread() {
        public void run() {
          if (m_activeBean == null)
            return;
          m_chooser.setDialogTitle(
            "Please choose file to serialize bean");
          m_chooser.setCurrentDirectory(m_currentDir);
          int result = m_chooser.showSaveDialog(
            BeanContainer.this);
          repaint();
          if (result != JFileChooser.APPROVE_OPTION)
            return;
          m_currentDir = m_chooser.getCurrentDirectory();
          File fChoosen = m_chooser.getSelectedFile();
          try {
            FileOutputStream fStream = 
              new FileOutputStream(fChoosen);
            ObjectOutput stream  =  
              new ObjectOutputStream(fStream);
            stream.writeObject(m_activeBean);
            stream.close();
            fStream.close();
          }
          catch (Exception ex) {
            ex.printStackTrace();
          JOptionPane.showMessageDialog(
            BeanContainer.this, "Error: "+ex.toString(),
            "Warning", JOptionPane.WARNING_MESSAGE);
          }
        }
      };
      newthread.start();
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);

  mFile.addSeparator();

  mItem = new JMenuItem("Exit");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      System.exit(0);
    }
  };
  mItem.addActionListener(lst);
  mFile.add(mItem);
  menuBar.add(mFile);
    
  JMenu mEdit = new JMenu("Edit");

  mItem = new JMenuItem("Delete");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      if (m_activeBean == null)
        return;
      Object obj = m_editors.get(m_activeBean);
      if (obj != null) {
        BeanEditor editor = (BeanEditor)obj;
        editor.dispose();
        m_editors.remove(m_activeBean);
      }
      getContentPane().remove(m_activeBean);
      m_activeBean = null;
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  mEdit.add(mItem);

  mItem = new JMenuItem("Properties...");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      if (m_activeBean == null)
        return;
      Object obj = m_editors.get(m_activeBean);
      if (obj != null) {
        BeanEditor editor = (BeanEditor)obj;
        editor.setVisible(true);
        editor.toFront();
      }
      else {
        BeanEditor editor = new BeanEditor(m_activeBean);
        m_editors.put(m_activeBean, editor);
      }
    }
  };
  mItem.addActionListener(lst);
  mEdit.add(mItem);
  menuBar.add(mEdit);

  JMenu mLayout = new JMenu("Layout");
  ButtonGroup group = new ButtonGroup();

  mItem = new JRadioButtonMenuItem("FlowLayout");
  mItem.setSelected(true);
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e){
      getContentPane().setLayout(new FlowLayout());
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);

  mItem = new JRadioButtonMenuItem("GridLayout");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e){
      int col = 3;
      int row = (int)Math.ceil(getContentPane().
        getComponentCount()/(double)col);
      getContentPane().setLayout(new GridLayout(row, col, 10, 10));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("BoxLayout - X");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new BoxLayout(
        getContentPane(), BoxLayout.X_AXIS));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("BoxLayout - Y");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new BoxLayout(
        getContentPane(), BoxLayout.Y_AXIS));
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);
    
  mItem = new JRadioButtonMenuItem("DialogLayout");
  lst = new ActionListener() { 
    public void actionPerformed(ActionEvent e) {
      getContentPane().setLayout(new DialogLayout());
      validate();
      repaint();
    }
  };
  mItem.addActionListener(lst);
  group.add(mItem);
  mLayout.add(mItem);

  menuBar.add(mLayout);

  return menuBar;
}

From source file:net.itransformers.topologyviewer.menu.handlers.graphTools.shortherstPathMenuHandlers.DijkstraWeightedShortestPathMenuHandler.java

@Override
public void actionPerformed(ActionEvent e) {
    final GraphViewerPanel viewerPanel = (GraphViewerPanel) frame.getTabbedPane().getSelectedComponent();
    final MyVisualizationViewer vv = (MyVisualizationViewer) viewerPanel.getVisualizationViewer();

    Collection<String> vertices = viewerPanel.getCurrentGraph().getVertices();
    String[] test = vertices.toArray(new String[0]);
    Arrays.sort(test);/*from  w  w w  .j a  v  a 2  s  .co m*/

    final String mFrom = (String) JOptionPane.showInputDialog(frame, "Choose A Node", "A Node",
            JOptionPane.PLAIN_MESSAGE, null, test, test[0]);
    final String mTo = (String) JOptionPane.showInputDialog(frame, "Choose B Node", "B Node",
            JOptionPane.PLAIN_MESSAGE, null, test, test[0]);
    String weightedKey = JOptionPane.showInputDialog(frame, "Enter Weighted Key", "Weighted Key",
            JOptionPane.QUESTION_MESSAGE);

    Transformer<String, Double> wtTransformer = new Transformer<String, Double>() {
        public Double transform(String edgeId) {

            return null;
        }
    };

    final Graph<String, String> mGraph = viewerPanel.getCurrentGraph();
    DijkstraShortestPath<String, String> alg = new DijkstraShortestPath(mGraph, wtTransformer);

    final List<String> mPred = alg.getPath(mFrom, mTo);
    //        System.out.println("The shortest unweighted path from" + mFrom +" to " + mTo + " is:");
    //        System.out.println(mPred.toString());

    if (mPred == null) {
        JOptionPane.showMessageDialog(frame,
                String.format("Shortest path between %s,%s is not found", mFrom, mTo), "Message",
                JOptionPane.INFORMATION_MESSAGE);
        return;
    }

    final Layout<String, String> layout = vv.getGraphLayout();
    for (final String edge : layout.getGraph().getEdges()) {
        if (mPred.contains(edge)) {
            vv.setEdgeStroke(edge, new BasicStroke(4f));

        }

    }
}

From source file:de.atomfrede.tools.evalutation.util.DialogUtil.java

public void showPlotTypeSelection() {
    SwingUtilities.invokeLater(new Runnable() {

        @Override/* ww w  .  j a v  a 2s.co m*/
        public void run() {
            Object[] types = PlotType.values();

            PlotType selectedType = (PlotType) JOptionPane.showInputDialog(frame,
                    "Select type of plot you want to create.", "Select Plot Type", JOptionPane.QUESTION_MESSAGE,
                    Icons.IC_INFORMATION_LARGE, types, types[0]);

            if (selectedType != null) {
                log.debug("Plot " + selectedType + " should be created.");
                switch (selectedType) {
                case SIMPLE: {
                    SimplePlotWizard wizard = new SimplePlotWizard();
                    // wizard.setSize(600, 800);
                    wizard.setSize(wizard.getPreferredSize());
                    wizard.setLocationRelativeTo(frame);
                    wizard.setModal(true);
                    showWizardDialog(wizard);
                    break;
                }
                case TIME: {
                    TimePlotWizard wizard = new TimePlotWizard();
                    // wizard.setSize(600, 800);
                    wizard.setSize(wizard.getPreferredSize());
                    wizard.setLocationRelativeTo(frame);
                    wizard.setModal(true);
                    showWizardDialog(wizard);
                    break;
                }
                default:
                    break;
                }
            }
        }
    });
}

From source file:StocksTable5.java

public void retrieveData() {
    SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy");
    String currentDate = frm.format(m_data.m_date);
    String result = (String) JOptionPane.showInputDialog(this, "Please enter date in form mm/dd/yyyy:", "Input",
            JOptionPane.INFORMATION_MESSAGE, null, null, currentDate);
    if (result == null)
        return;//from w  ww. j a  v a 2 s  .c  o m

    java.util.Date date = null;
    try {
        date = frm.parse(result);
    } catch (java.text.ParseException ex) {
        date = null;
    }

    if (date == null) {
        JOptionPane.showMessageDialog(this, result + " is not a valid date", "Warning",
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    switch (m_data.retrieveData(date)) {
    case 0: // Ok with data
        m_title.setText(m_data.getTitle());
        m_table.tableChanged(new TableModelEvent(m_data));
        m_table.repaint();
        break;
    case 1: // No data
        JOptionPane.showMessageDialog(this, "No data found for " + result, "Warning",
                JOptionPane.WARNING_MESSAGE);
        break;
    case -1: // Error
        JOptionPane.showMessageDialog(this, "Error retrieving data", "Warning", JOptionPane.WARNING_MESSAGE);
        break;
    }
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}

From source file:org.cds06.speleograph.graph.SeriesMenu.java

private JPopupMenu createPopupMenuForSeries(final Series series) {

    if (series == null)
        return new JPopupMenu();

    final JPopupMenu menu = new JPopupMenu(series.getName());

    menu.removeAll();// ww w  .ja  v  a  2s.co m

    menu.add(new AbstractAction() {
        {
            putValue(NAME, "Renommer la srie");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            menu.setVisible(false);
            String newName = "";
            while (newName == null || newName.equals("")) {
                newName = (String) JOptionPane.showInputDialog(application,
                        "Entrez un nouveau nom pour la srie", null, JOptionPane.QUESTION_MESSAGE, null, null,
                        series.getName());
            }
            series.setName(newName);
        }
    });

    if (series.hasOwnAxis()) {
        menu.add(new AbstractAction() {

            {
                putValue(NAME, "Supprimer l'axe spcifique");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(application, "tes vous sr de vouloir supprimer cet axe ?",
                        "Confirmation", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                    series.setAxis(null);
                }
            }
        });
    } else {
        menu.add(new JMenuItem(new AbstractAction() {

            {
                putValue(NAME, "Crer un axe spcifique pour la srie");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                String name = JOptionPane.showInputDialog(application, "Quel titre pour cet axe ?",
                        series.getAxis().getLabel());
                if (name == null || "".equals(name))
                    return; // User has canceled
                series.setAxis(new NumberAxis(name));
            }
        }));
    }

    menu.add(new SetTypeMenu(series));

    if (series.isWater()) {
        menu.addSeparator();
        menu.add(new SumOnPeriodAction(series));
        menu.add(new CreateCumulAction(series));
    }
    if (series.isWaterCumul()) {
        menu.addSeparator();
        menu.add(new SamplingAction(series));
    }

    if (series.isPressure()) {
        menu.addSeparator();
        menu.add(new CorrelateAction(series));
        menu.add(new WaterHeightAction(series));
    }

    menu.addSeparator();

    menu.add(new AbstractAction() {
        {
            String name;
            if (series.canUndo())
                name = "Annuler " + series.getItemsName();
            else
                name = series.getLastUndoName();

            putValue(NAME, name);

            if (series.canUndo())
                setEnabled(true);
            else {
                setEnabled(false);
            }

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            series.undo();
        }
    });

    menu.add(new AbstractAction() {
        {
            String name;
            if (series.canRedo()) {
                name = "Refaire " + series.getNextRedoName();
                setEnabled(true);
            } else {
                name = series.getNextRedoName();
                setEnabled(false);
            }

            putValue(NAME, name);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            series.redo();
        }
    });

    menu.add(new AbstractAction() {
        {
            putValue(NAME, I18nSupport.translate("menus.serie.resetSerie"));
            if (series.canUndo())
                setEnabled(true);
            else
                setEnabled(false);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            series.reset();
        }
    });

    menu.add(new LimitDateRangeAction(series));

    menu.add(new HourSettingAction(series));

    menu.addSeparator();

    {
        JMenuItem deleteItem = new JMenuItem("Supprimer la srie");
        deleteItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(application,
                        "tes-vous sur de vouloir supprimer cette srie ?\n"
                                + "Cette action est dfinitive.",
                        "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
                    series.delete();
                }
            }
        });
        menu.add(deleteItem);
    }

    menu.addSeparator();

    {
        final JMenuItem up = new JMenuItem("Remonter dans la liste"),
                down = new JMenuItem("Descendre dans la liste");
        ActionListener listener = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().equals(up)) {
                    series.upSeriesInList();
                } else {
                    series.downSeriesInList();
                }
            }
        };
        up.addActionListener(listener);
        down.addActionListener(listener);
        if (series.isFirst()) {
            menu.add(down);
        } else if (series.isLast()) {
            menu.add(up);
        } else {
            menu.add(up);
            menu.add(down);
        }
    }

    menu.addSeparator();

    {
        menu.add(new SeriesInfoAction(series));
    }

    {
        JMenuItem colorItem = new JMenuItem("Couleur de la srie");
        colorItem.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                series.setColor(JColorChooser.showDialog(application,
                        I18nSupport.translate("actions.selectColorForSeries"), series.getColor()));
            }
        });
        menu.add(colorItem);
    }

    {
        JMenu plotRenderer = new JMenu("Affichage de la srie");
        final ButtonGroup modes = new ButtonGroup();
        java.util.List<DrawStyle> availableStyles;
        if (series.isMinMax()) {
            availableStyles = DrawStyles.getDrawableStylesForHighLow();
        } else {
            availableStyles = DrawStyles.getDrawableStyles();
        }
        for (final DrawStyle s : availableStyles) {
            final JRadioButtonMenuItem item = new JRadioButtonMenuItem(DrawStyles.getHumanCheckboxText(s));
            item.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    if (item.isSelected())
                        series.setStyle(s);
                }
            });
            modes.add(item);
            if (s.equals(series.getStyle())) {
                modes.setSelected(item.getModel(), true);
            }
            plotRenderer.add(item);
        }
        menu.add(plotRenderer);
    }
    menu.addSeparator();

    menu.add(new AbstractAction() {
        {
            putValue(Action.NAME, "Fermer le fichier");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(application,
                    "tes-vous sur de vouloir fermer toutes les sries du fichier ?", "Confirmation",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
                final File f = series.getOrigin();
                for (final Series s : Series.getInstances().toArray(new Series[Series.getInstances().size()])) {
                    if (s.getOrigin().equals(f))
                        s.delete();
                }
            }
        }
    });

    return menu;
}

From source file:net.sf.jabref.gui.UrlDragDrop.java

@Override
public void drop(DropTargetDropEvent dtde) {
    Transferable tsf = dtde.getTransferable();
    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    //try with an URL
    DataFlavor dtURL = null;/* w  w w. j  a v  a 2  s  .co m*/
    try {
        dtURL = new DataFlavor("application/x-java-url; class=java.net.URL");
    } catch (ClassNotFoundException e) {
        LOGGER.warn("Could not find DropTargetDropEvent class.", e);
    }
    try {
        URL url = (URL) tsf.getTransferData(dtURL);
        JOptionChoice res = (JOptionChoice) JOptionPane.showInputDialog(editor, "",
                Localization.lang("Select action"), JOptionPane.QUESTION_MESSAGE, null,
                new JOptionChoice[] { new JOptionChoice(Localization.lang("Insert URL"), 0),
                        new JOptionChoice(Localization.lang("Download file"), 1) },
                new JOptionChoice(Localization.lang("Insert URL"), 0));
        if (res != null) {
            switch (res.getId()) {
            //insert URL
            case 0:
                feditor.setText(url.toString());
                editor.updateField(feditor);
                break;
            //download file
            case 1:
                try {
                    //auto filename:
                    File file = new File(new File(Globals.prefs.get("pdfDirectory")),
                            editor.getEntry().getCiteKey() + ".pdf");
                    frame.output(Localization.lang("Downloading..."));
                    MonitoredURLDownload.buildMonitoredDownload(editor, url).downloadToFile(file);
                    frame.output(Localization.lang("Download completed"));
                    feditor.setText(file.toURI().toURL().toString());
                    editor.updateField(feditor);

                } catch (IOException ioex) {
                    LOGGER.error("Error while downloading file.", ioex);
                    JOptionPane.showMessageDialog(editor, Localization.lang("File download"),
                            Localization.lang("Error while downloading file:" + ioex.getMessage()),
                            JOptionPane.ERROR_MESSAGE);
                }
                break;
            default:
                LOGGER.warn("Unknown selection (should not happen)");
                break;
            }
        }
        return;
    } catch (UnsupportedFlavorException nfe) {
        // not an URL then...
        LOGGER.warn("Could not parse URL.", nfe);
    } catch (IOException ioex) {
        LOGGER.warn("Could not perform drag and drop.", ioex);
    }

    try {
        //try with a File List
        @SuppressWarnings("unchecked")
        List<File> filelist = (List<File>) tsf.getTransferData(DataFlavor.javaFileListFlavor);
        if (filelist.size() > 1) {
            JOptionPane.showMessageDialog(editor, Localization.lang("Only one item is supported"),
                    Localization.lang("Drag and Drop Error"), JOptionPane.ERROR_MESSAGE);
            return;
        }
        File fl = filelist.get(0);
        feditor.setText(fl.toURI().toURL().toString());
        editor.updateField(feditor);

    } catch (UnsupportedFlavorException nfe) {
        JOptionPane.showMessageDialog(editor, Localization.lang("Operation not supported"),
                Localization.lang("Drag and Drop Error"), JOptionPane.ERROR_MESSAGE);
        LOGGER.warn("Could not perform drag and drop.", nfe);
    } catch (IOException ioex) {
        LOGGER.warn("Could not perform drag and drop.", ioex);
    }

}

From source file:com.frostwire.gui.library.LibraryUtils.java

public static void createNewPlaylist(final List<? extends AbstractLibraryTableDataLine<?>> lines) {
    String playlistName = (String) JOptionPane.showInputDialog(GUIMediator.getAppFrame(),
            I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null,
            calculateName(lines));/* w  w w. ja va  2  s  .  c o m*/

    if (playlistName != null && playlistName.length() > 0) {
        final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
        playlist.save();
        LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
        LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
        Thread t = new Thread(new Runnable() {
            public void run() {
                addToPlaylist(playlist, lines);
                playlist.save();
                asyncAddToPlaylistFinalizer(playlist);
            }
        }, "createNewPlaylist");
        t.setDaemon(true);
        t.start();
    }
}

From source file:com.frostwire.gui.library.LibraryUtils.java

public static void createNewPlaylist(final File[] files, final boolean starred) {

    final StringBuilder plBuilder = new StringBuilder();

    GUIMediator.safeInvokeAndWait(new Runnable() {

        @Override/*from   www .  j a va 2s.  co m*/
        public void run() {
            String input = (String) JOptionPane.showInputDialog(GUIMediator.getAppFrame(),
                    I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null,
                    calculateName(files));
            if (!StringUtils.isNullOrEmpty(input, true)) {
                plBuilder.append(input);
            }
        }
    });

    String playlistName = plBuilder.toString();

    if (playlistName != null && playlistName.length() > 0) {
        GUIMediator.instance().setWindow(GUIMediator.Tabs.LIBRARY);
        final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
        playlist.save();

        GUIMediator.safeInvokeLater(new Runnable() {

            @Override
            public void run() {
                LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
                LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
            }
        });

        Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    Set<File> ignore = TorrentUtil.getIgnorableFiles();
                    addToPlaylist(playlist, files, starred, ignore);
                    playlist.save();
                } finally {
                    asyncAddToPlaylistFinalizer(playlist);
                }
            }
        }, "createNewPlaylist");
        t.setDaemon(true);
        t.start();
    }
}