Example #1
0
 void enableButtons(JList list) {
   int nSelected = list.getSelectedIndices().length;
   int nListed = list.getModel().getSize();
   saveButton.setEnabled(nListed > 0);
   deleteInstanceButton.setEnabled(nSelected > 0);
   showInstanceButton.setEnabled(nSelected == 1);
 }
Example #2
0
  // Listener method for list selection changes.
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {

      if (list.getSelectedIndex() == -1) {
        // No selection: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);
        nameField.setText("");

      } else if (list.getSelectedIndices().length > 1) {
        // Multiple selection: disable up and down buttons.
        deleteButton.setEnabled(true);
        upButton.setEnabled(false);
        downButton.setEnabled(false);

      } else {
        // Single selection: permit all operations.
        deleteButton.setEnabled(true);
        upButton.setEnabled(true);
        downButton.setEnabled(true);
        nameField.setText(list.getSelectedValue().toString());
      }
    }
  }
Example #3
0
  public static Map[] showOpenMapDialog(final JFrame owner) throws IOException {
    final JFileChooser ch = new JFileChooser();
    if (config.getFile("mapLastOpenDir") != null) {
      ch.setCurrentDirectory(config.getFile("mapLastOpenDir"));
    }
    ch.setDialogType(JFileChooser.OPEN_DIALOG);
    ch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (ch.showOpenDialog(MainFrame.getInstance()) != JFileChooser.APPROVE_OPTION) {
      return null;
    }
    final File dir = ch.getSelectedFile();
    config.set("mapLastOpenDir", dir);
    final String[] maps = dir.list(FILTER_TILES);
    for (int i = 0; i < maps.length; ++i) {
      maps[i] = maps[i].substring(0, maps[i].length() - MapIO.EXT_TILE.length());
    }
    final JDialog dialog = new JDialog(owner, Lang.getMsg("gui.chooser"));
    dialog.setModal(true);
    dialog.setLocationRelativeTo(null);
    dialog.setLayout(new BorderLayout());

    final JList list = new JList(maps);
    final JButton btn = new JButton(Lang.getMsg("gui.chooser.Ok"));

    btn.addActionListener(
        new AbstractAction() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            if (list.getSelectedValue() != null) {
              dialog.setVisible(false);
            }
          }
        });

    dialog.add(new JScrollPane(list), BorderLayout.CENTER);
    dialog.add(btn, BorderLayout.SOUTH);
    dialog.pack();
    dialog.setVisible(true);
    dialog.dispose();

    Map[] loadedMaps = new Map[list.getSelectedIndices().length];
    for (int i = 0; i < list.getSelectedIndices().length; i++) {
      loadedMaps[i] = MapIO.loadMap(dir.getPath(), (String) list.getSelectedValues()[i]);
    }
    return loadedMaps;
  }
Example #4
0
  public Object[] getSelectedElements() {
    ArrayList<Object> ret = new ArrayList<Object>();
    int[] indexes = lst.getSelectedIndices();
    for (int index : indexes) {
      ret.add(ids[index]);
    }

    return ret.toArray();
  }
Example #5
0
 public void valueChanged(ListSelectionEvent e) {
   int tmp = 0;
   String stmp = "您目前选取:";
   int[] index = list.getSelectedIndices();
   for (int i = 0; i < index.length; i++) {
     tmp = index[i];
     stmp = stmp + s[tmp] + "  ";
   }
   label.setText(stmp);
 }
  @NotNull
  public static <T extends PsiElement> JBPopup getPsiElementPopup(
      @NotNull T[] elements,
      @NotNull final PsiElementListCellRenderer<T> renderer,
      @Nullable final String title,
      @NotNull final PsiElementProcessor<T> processor,
      @Nullable final T selection) {
    final JList list =
        new JBListWithHintProvider(elements) {
          @Nullable
          @Override
          protected PsiElement getPsiElementForHint(Object selectedValue) {
            return (PsiElement) selectedValue;
          }
        };
    list.setCellRenderer(renderer);

    list.setFont(EditorUtil.getEditorFont());

    if (selection != null) {
      list.setSelectedValue(selection, true);
    }

    final Runnable runnable =
        () -> {
          int[] ids = list.getSelectedIndices();
          if (ids == null || ids.length == 0) return;
          for (Object element : list.getSelectedValues()) {
            if (element != null) {
              processor.execute((T) element);
            }
          }
        };

    PopupChooserBuilder builder = new PopupChooserBuilder(list);
    if (title != null) {
      builder.setTitle(title);
    }
    renderer.installSpeedSearch(builder, true);

    JBPopup popup = builder.setItemChoosenCallback(runnable).createPopup();

    builder.getScrollPane().setBorder(null);
    builder.getScrollPane().setViewportBorder(null);

    return popup;
  }
  private void removeButtonActionPerformed() {
    JList selectedList = getSelectedRobotsList();
    SelectedRobotsModel selectedModel = (SelectedRobotsModel) selectedList.getModel();
    int sel[] = selectedList.getSelectedIndices();

    for (int i = 0; i < sel.length; i++) {
      selectedRobots.remove(sel[i] - i);
    }
    selectedList.clearSelection();
    selectedModel.changed();
    fireStateChanged();
    if (selectedModel.getSize() < minRobots || selectedModel.getSize() > maxRobots) {
      showWrongNumInstructions();
    } else {
      showInstructions();
    }
  }
  /** Export a list of user selected projections */
  public void doExport() {
    List projections = getProjections();

    Vector<String> projectionNames = new Vector<>(projections.size());
    for (int i = 0; i < projections.size(); i++) {
      ProjectionImpl projection = (ProjectionImpl) projections.get(i);
      projectionNames.add(projection.getName());
    }

    JList<String> jlist = new JList<>(projectionNames);
    JPanel contents =
        GuiUtils.topCenter(
            GuiUtils.cLabel("Please select the projections you want to export"),
            GuiUtils.makeScrollPane(jlist, 200, 400));

    if (!GuiUtils.showOkCancelDialog(null, "Export Projections", contents, null)) {
      return;
    }

    int[] indices = jlist.getSelectedIndices();
    if ((indices == null) || (indices.length == 0)) {
      return;
    }
    List<ProjectionImpl> selected = new ArrayList<>(indices.length);
    for (int i = 0; i < indices.length; i++) {
      selected.add((ProjectionImpl) projections.get(indices[i]));
    }
    String xml = (new XmlEncoder()).toXml(selected);
    String filename = FileManager.getWriteFile(FileManager.FILTER_XML, FileManager.SUFFIX_XML);
    if (filename == null) {
      return;
    }
    try {
      IOUtil.writeFile(filename, xml);
    } catch (Exception exc) {
      LogUtil.logException("Writing projection file: " + filename, exc);
    }
  }
  @NotNull
  @Override
  public RelativePoint guessBestPopupLocation(@NotNull final JComponent component) {
    Point popupMenuPoint = null;
    final Rectangle visibleRect = component.getVisibleRect();
    if (component instanceof JList) { // JList
      JList list = (JList) component;
      int firstVisibleIndex = list.getFirstVisibleIndex();
      int lastVisibleIndex = list.getLastVisibleIndex();
      int[] selectedIndices = list.getSelectedIndices();
      for (int index : selectedIndices) {
        if (firstVisibleIndex <= index && index <= lastVisibleIndex) {
          Rectangle cellBounds = list.getCellBounds(index, index);
          popupMenuPoint =
              new Point(visibleRect.x + visibleRect.width / 4, cellBounds.y + cellBounds.height);
          break;
        }
      }
    } else if (component instanceof JTree) { // JTree
      JTree tree = (JTree) component;
      int[] selectionRows = tree.getSelectionRows();
      if (selectionRows != null) {
        Arrays.sort(selectionRows);
        for (int i = 0; i < selectionRows.length; i++) {
          int row = selectionRows[i];
          Rectangle rowBounds = tree.getRowBounds(row);
          if (visibleRect.contains(rowBounds)) {
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
            break;
          }
        }
        if (popupMenuPoint == null) { // All selected rows are out of visible rect
          Point visibleCenter =
              new Point(
                  visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
          double minDistance = Double.POSITIVE_INFINITY;
          int bestRow = -1;
          Point rowCenter;
          double distance;
          for (int i = 0; i < selectionRows.length; i++) {
            int row = selectionRows[i];
            Rectangle rowBounds = tree.getRowBounds(row);
            rowCenter =
                new Point(rowBounds.x + rowBounds.width / 2, rowBounds.y + rowBounds.height / 2);
            distance = visibleCenter.distance(rowCenter);
            if (minDistance > distance) {
              minDistance = distance;
              bestRow = row;
            }
          }

          if (bestRow != -1) {
            Rectangle rowBounds = tree.getRowBounds(bestRow);
            tree.scrollRectToVisible(
                new Rectangle(
                    rowBounds.x,
                    rowBounds.y,
                    Math.min(visibleRect.width, rowBounds.width),
                    rowBounds.height));
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
          }
        }
      }
    } else if (component instanceof JTable) {
      JTable table = (JTable) component;
      int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
      int row =
          Math.max(
              table.getSelectionModel().getLeadSelectionIndex(),
              table.getSelectionModel().getAnchorSelectionIndex());
      Rectangle rect = table.getCellRect(row, column, false);
      if (!visibleRect.intersects(rect)) {
        table.scrollRectToVisible(rect);
      }
      popupMenuPoint = new Point(rect.x, rect.y + rect.height);
    } else if (component instanceof PopupOwner) {
      popupMenuPoint = ((PopupOwner) component).getBestPopupPosition();
    }
    if (popupMenuPoint == null) {
      popupMenuPoint =
          new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
    }

    return new RelativePoint(component, popupMenuPoint);
  }
Example #10
0
  public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();

    if (src == binfo) {
      JOptionPane.showMessageDialog(
          frame,
          "Programme crée par Sarathai\n"
              + "Licence creative commons\n"
              + "\n"
              + "Pour envoyer des fichiers sur le serveur, cliquer d'abord sur le bouton ajouter,\n"
              + "puis sélectionnez le dossier ou fichier à ajouter. Répétez cette opération autant de foi que nécessaire.\n"
              + "Puis cliquez sur le bouton envoyer en ayant d'abord rempli les champs de l'adresse ip et du port.\n"
              + "\n"
              + "Pour recevoir des fichiers sauvegardés sur le serveur, cliquez sur le bouton recevoir,\n"
              + "puis sélectionnez le ou les fichier(s) voulu(s) dans la liste de gauche, et enfin recliquez\n"
              + "sur le bouton recevoir pour importer les fichiers.\n"
              + "\n"
              + "Pour toutes les infos, bien lire le texte qui s'affiche dans le champ de texte en bas.",
          "Informations",
          JOptionPane.INFORMATION_MESSAGE);
    } else if (src == ajouter) {
      JFileChooser chooser = new JFileChooser();
      chooser.setFileFilter(chooser.getAcceptAllFileFilter());
      chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

      int i = chooser.showOpenDialog(Fenetre.frame);
      if (i == JFileChooser.APPROVE_OPTION) {
        frame.setCursor(waitCursor);

        File file = chooser.getSelectedFile();

        if (file.isDirectory()) {
          name = file.getAbsolutePath().toString() + sep;
          selection.addElement(name);
          new WhatIDo("Ajouté à la séléction", name);
        } else {
          name = file.getAbsolutePath().toString();
          selection.addElement(name);
          new WhatIDo("Ajouté à la séléction", name);
        }
        liste.updateUI();
        enlever.setEnabled(true);
        frame.setCursor(Cursor.getDefaultCursor());
      }
    } else if (src == enlever) {
      try {
        int j = liste.getSelectedIndex();
        new WhatIDo("Supprimé de la séléction", selection.elementAt(j).toString());
        selection.removeElementAt(j);
      } catch (ArrayIndexOutOfBoundsException e1) {
        new WhatIDo("Supprimé de la séléction", selection.elementAt(0).toString());
        selection.removeElementAt(0);
      }
      if (selection.size() == 0) {
        selection.clear();
        liste.clearSelection();
        enlever.setEnabled(false);
      }
      liste.updateUI();
    } else if (src == bquitter) {
      System.exit(0);
    } else if (src == bnouveau) {
      selection.clear();
      liste.clearSelection();
      liste.updateUI();
      new WhatIDo("Nouvelle sauvegarde");
    } else if (src == benvoyer) {
      if (!selection.isEmpty()) {
        new Envoyer(selection);
      } else {
        new WhatIDo("Veuillez ajouter des fichiers ou dossiers");
      }
    } else if (src == brecevoir) {
      if (!liste.isSelectionEmpty()) {
        Vector<String> vec = new Vector<String>();
        for (int i : liste.getSelectedIndices()) {
          vec.addElement(selection.elementAt(i));
        }
        new Recevoir(vec);
      } else {
        new Recevoir();
      }
    }
  }
Example #11
0
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == remoteAppletPath) {//apparently no events are fired to reach this, maybe "enter" does it
      String path = remoteAppletPath.getText();
      WebExport.setAppletPath(path, true);
      return;
    }

    if (e.getSource() == localAppletPath) {//apparently no events are fired to reach this, maybe "enter" does it
      String path = localAppletPath.getText();
      WebExport.setAppletPath(path, false);
      return;
    }

    //Handle open button action.
    if (e.getSource() == addInstanceButton) {
      //make dialog to get name for instance
      //create an instance with this name.  Each instance is just a container for a string with the Jmol state
      //which contains the full information on the file that is loaded and manipulations done.
      String label = (instanceList.getSelectedIndices().length != 1 ? ""
          : getInstanceName(-1));
      String name = JOptionPane.showInputDialog(
          GT._("Give the occurrence of Jmol a name:"), label);
      if (name == null)
        return;
      //need to get the script...
      String script = viewer.getStateInfo();
      if (script == null) {
        LogPanel.log("Error trying to get Jmol State within pop_in_Jmol.");
      }
      DefaultListModel listModel = (DefaultListModel) instanceList.getModel();
      int width = 300;
      int height = 300;
      if (appletSizeSpinnerH != null) {
        width = ((SpinnerNumberModel) (appletSizeSpinnerW.getModel()))
            .getNumber().intValue();
        height = ((SpinnerNumberModel) (appletSizeSpinnerH.getModel()))
            .getNumber().intValue();
      }
      JmolInstance instance = new JmolInstance(viewer, name, script, width, height);
      if (instance == null) {
        LogPanel
            .log(GT._("Error creating new instance containing script(s) and image."));
      }

      int i;
      for (i = instanceList.getModel().getSize(); --i >= 0;)
        if (getInstanceName(i).equals(instance.name))
          break;
      if (i < 0) {
        i = listModel.getSize();
        listModel.addElement(instance);
        LogPanel.log(GT._("added Instance {0}", instance.name));
      } else {
        listModel.setElementAt(instance, i);
        LogPanel.log(GT._("updated Instance {0}", instance.name));
      }
      instanceList.setSelectedIndex(i);
      syncLists();
      return;
    }

    if (e.getSource() == deleteInstanceButton) {
      DefaultListModel listModel = (DefaultListModel) instanceList.getModel();
      //find out which are selected and remove them.
      int[] todelete = instanceList.getSelectedIndices();
      int nDeleted = 0;
      for (int i = 0; i < todelete.length; i++){
        JmolInstance instance = (JmolInstance) listModel.get(todelete[i]);
        try {
          instance.delete();
        } catch (IOException err) {
          LogPanel.log(err.getMessage());
        }
        listModel.remove(todelete[i] - nDeleted++);
      }
      syncLists();
      return;
    }

    if (e.getSource() == showInstanceButton) {
      DefaultListModel listModel = (DefaultListModel) instanceList.getModel();
      //find out which are selected and remove them.
      int[] list = instanceList.getSelectedIndices();
      if (list.length != 1)
        return;
      JmolInstance instance = (JmolInstance) listModel.get(list[0]);
      viewer.evalStringQuiet(")" + instance.script); //leading paren disabled history
      return;
    }

    if (e.getSource() == saveButton) {
      fc.setDialogTitle(GT._("Select a directory to create or an HTML file to save"));
      int returnVal = fc.showSaveDialog(this);
      if (returnVal != JFileChooser.APPROVE_OPTION)
        return;
      File file = fc.getSelectedFile();
      boolean retVal = true;
      try {
        String path = remoteAppletPath.getText();
        WebExport.setAppletPath(path, true);
        path = localAppletPath.getText();
        WebExport.setAppletPath(path, false);
        String authorName = pageAuthorName.getText();
        WebExport.setWebPageAuthor(authorName);
        retVal = fileWriter(file, instanceList);
      } catch (IOException IOe) {
        LogPanel.log(IOe.getMessage());
      }
      if (!retVal) {
        LogPanel.log(GT._("Call to FileWriter unsuccessful."));
      }
    }
    if (e.getSource() == helpButton){
      HelpDialog webExportHelp = new HelpDialog(WebExport.getFrame(), 
          WebExport.getHtmlResource(this, panelName + "_instructions"));
      webExportHelp.setVisible(true);
      webExportHelp.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
  }
Example #12
-1
 protected Transferable createTransferable(JComponent c) {
   if (c instanceof JList) {
     source = (JList) c;
     sourceIndices = source.getSelectedIndices();
     Object[] values = source.getSelectedValues();
     if (values == null || values.length == 0) {
       return null;
     }
     ArrayList alist = new ArrayList(values.length);
     for (int i = 0; i < values.length; i++) {
       Object o = values[i];
       String str = o.toString();
       if (str == null)
         str = "";
       alist.add(str);
     }
     return new ArrayListTransferable(alist);
   }
   return null;
 }