コード例 #1
0
    public void valueChanged(ListSelectionEvent evt) {
      if (!evt.getValueIsAdjusting()) {
        JFileChooser chooser = getFileChooser();
        FileSystemView fsv = chooser.getFileSystemView();
        JList list = (JList) evt.getSource();

        int fsm = chooser.getFileSelectionMode();
        boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY);

        if (chooser.isMultiSelectionEnabled()) {
          File[] files = null;
          Object[] objects = list.getSelectedValues();
          if (objects != null) {
            if (objects.length == 1
                && ((File) objects[0]).isDirectory()
                && chooser.isTraversable(((File) objects[0]))
                && (useSetDirectory || !fsv.isFileSystem(((File) objects[0])))) {
              setDirectorySelected(true);
              setDirectory(((File) objects[0]));
            } else {
              ArrayList<File> fList = new ArrayList<File>(objects.length);
              for (Object object : objects) {
                File f = (File) object;
                boolean isDir = f.isDirectory();
                if ((chooser.isFileSelectionEnabled() && !isDir)
                    || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) {
                  fList.add(f);
                }
              }
              if (fList.size() > 0) {
                files = fList.toArray(new File[fList.size()]);
              }
              setDirectorySelected(false);
            }
          }
          chooser.setSelectedFiles(files);
        } else {
          File file = (File) list.getSelectedValue();
          if (file != null
              && file.isDirectory()
              && chooser.isTraversable(file)
              && (useSetDirectory || !fsv.isFileSystem(file))) {

            setDirectorySelected(true);
            setDirectory(file);
            if (usesSingleFilePane) {
              chooser.setSelectedFile(null);
            }
          } else {
            setDirectorySelected(false);
            if (file != null) {
              chooser.setSelectedFile(file);
            }
          }
        }
      }
    }
コード例 #2
0
    public void actionPerformed(ActionEvent e) {
      if (readOnly) {
        return;
      }
      JFileChooser fc = getFileChooser();
      File currentDirectory = fc.getCurrentDirectory();

      if (!currentDirectory.exists()) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderParentDoesntExistText,
            newFolderParentDoesntExistTitleText,
            JOptionPane.WARNING_MESSAGE);
        return;
      }

      File newFolder;
      try {
        newFolder = fc.getFileSystemView().createNewFolder(currentDirectory);
        if (fc.isMultiSelectionEnabled()) {
          fc.setSelectedFiles(new File[] {newFolder});
        } else {
          fc.setSelectedFile(newFolder);
        }
      } catch (IOException exc) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderErrorText + newFolderErrorSeparator + exc,
            newFolderErrorText,
            JOptionPane.ERROR_MESSAGE);
        return;
      }

      fc.rescanCurrentDirectory();
    }
コード例 #3
0
ファイル: ScreenShotTest.java プロジェクト: okeeper/jietu
  // 保存图像到文件
  public void saveImage() throws IOException {
    JFileChooser jfc = new JFileChooser();
    jfc.setDialogTitle("保存");

    // 文件过滤器,用户过滤可选择文件
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");
    jfc.setFileFilter(filter);

    // 初始化一个默认文件(此文件会生成到桌面上)
    SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
    String fileName = sdf.format(new Date());
    File filePath = FileSystemView.getFileSystemView().getHomeDirectory();
    File defaultFile = new File(filePath + File.separator + fileName + ".jpg");
    jfc.setSelectedFile(defaultFile);

    int flag = jfc.showSaveDialog(this);
    if (flag == JFileChooser.APPROVE_OPTION) {
      File file = jfc.getSelectedFile();
      String path = file.getPath();
      // 检查文件后缀,放置用户忘记输入后缀或者输入不正确的后缀
      if (!(path.endsWith(".jpg") || path.endsWith(".JPG"))) {
        path += ".jpg";
      }
      // 写入文件
      ImageIO.write(saveImage, "jpg", new File(path));
      System.exit(0);
    }
  }
コード例 #4
0
  public void saveScriptToFile(
      String code, String filename, Component parent, PropertyPanelController cont) {

    JFileChooser fileChooser = new JFileChooser();

    fileChooser.setDialogTitle("Save to file");
    String currentDirectory = new File(".").getAbsolutePath();

    fileChooser.setSelectedFile(new File(currentDirectory, filename));
    fileChooser.setName(FILE_CHOOSER);

    if (fileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();

      try {
        if (file.createNewFile()) {
          OutputStream out = new FileOutputStream(file);
          out.write(code.getBytes());
          out.close();

          cont.fileSaveSuccess(file.getAbsolutePath());
        }
      } catch (IOException e) {
        Log.error(e.getMessage(), e);

        cont.fileSaveError(file.getAbsolutePath());
      }
    }
  }
コード例 #5
0
ファイル: Decipher.java プロジェクト: johnperry/MIRC1
 /**
  * The ActionListener implementation
  *
  * @param event the event.
  */
 public void actionPerformed(ActionEvent event) {
   String searchText = textField.getText().trim();
   if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) {
     textPane.setText("Blank search text is not allowed for large IdTables.");
   } else {
     File outputFile = null;
     if (saveAs.isSelected()) {
       outputFile = chooser.getSelectedFile();
       if (outputFile != null) {
         String name = outputFile.getName();
         int k = name.lastIndexOf(".");
         if (k != -1) name = name.substring(0, k);
         name += ".txt";
         File parent = outputFile.getAbsoluteFile().getParentFile();
         outputFile = new File(parent, name);
         chooser.setSelectedFile(outputFile);
       }
       if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0);
       outputFile = chooser.getSelectedFile();
     }
     textPane.setText("");
     Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile);
     searcher.start();
   }
 }
コード例 #6
0
      public void actionPerformed(ActionEvent evt) {
        File directory = new File(field.getText());
        JFileChooser chooser = new JFileChooser(directory.getParent());
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setSelectedFile(directory);

        if (chooser.showOpenDialog(SwingInstall.this) == JFileChooser.APPROVE_OPTION)
          field.setText(chooser.getSelectedFile().getPath());
      }
コード例 #7
0
ファイル: OpenFileDir.java プロジェクト: NCIP/dwd
  /**
   * Use a JFileChooser in Save mode to select files to open. Use a filter for FileFilter subclass
   * to select for "*.java" files. If a file is selected, then this file will be used as final
   * output
   */
  boolean saveFile() {
    File file = null;
    JFileChooser fc = new JFileChooser();

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(fJavaFilter);

    // Set to a default name for save.
    fc.setSelectedFile(fFile);

    // Open chooser dialog
    int result = fc.showSaveDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
      return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
      fFile = fc.getSelectedFile();
      String textFile = fFile.toString();
      if (fileNo.equalsIgnoreCase("SAVE")) {
        UpLoadFile.outputfile.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE2")) {
        UpLoadMAGEMLFile.outputfile1.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE3")) {
        UpLoadMAGEMLFile.outputfile2.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVEJPAG")) {
        JPEGFileName = textFile;
        // System.out.println ("JPG filename OpenFileDir= " +JPEGFileName);
        File fFile = new File(JPEGFileName);
        if (fFile.exists()) {
          int response =
              JOptionPane.showConfirmDialog(
                  null,
                  "Overwrite existing file " + JPEGFileName + " ??",
                  "Confirm Overwrite",
                  JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          if (response == JOptionPane.CANCEL_OPTION) {
            /* go back to reload the file*/
            return false;
          }
        }
        SetUpPlotWindow.saveComponentAsJPEG(SetUpPlotWindow.content, JPEGFileName);
      }
      return true;

    } else {
      return false;
    }
  } // saveFile
コード例 #8
0
ファイル: TabView.java プロジェクト: linvald/JarFileAnalyser
  /* (non-Javadoc)
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();
    if (o instanceof JMenuItem) {
      JMenuItem sender = (JMenuItem) o;
      String name = sender.getText();
      if (name.equals("close")) {
        tabbedPane.removeTabAt(tabbedPane.getSelectedIndex());
      } else if (name.equals("save")) {
        int index = tabbedPane.getSelectedIndex();
        Component c = tabbedPane.getComponent(index);
        Point p = c.getLocation();
        Component t = tabbedPane.getComponentAt(new Point(p.x + 20, p.y + 30));
        if (t instanceof TextView) {
          TextView text = (TextView) t;
          // String code = text.getText();
          // save the code
          // saveTab(code);
        }
        if (t instanceof HTMLTextView) {
          HTMLTextView text = (HTMLTextView) t;
          fileChooser.setSelectedFile(new File(text.node.getName()));
          int returnVal = fileChooser.showSaveDialog(this);

          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fileChooser.getSelectedFile();

            // save the code
            String fileType =
                f.getName().substring(f.getName().lastIndexOf("."), f.getName().length());
            if (fileType.indexOf("htm") != -1) {
              // save as html
              String code = text.getText();
              saveTab(code, f);
            } else if (fileType.indexOf("java") != -1) {
              // save as java
              String code = text.getUnModyfiedContent();
              saveTab(code, f);
            } else if (text.node.fileType.indexOf(FileTypes.MANIFEST) != -1
                || text.node.fileType.indexOf(FileTypes.MANIFEST2) != -1) {
              String code = text.getUnModyfiedContent();
              saveTab(code, f);
              System.out.println("Saved manifest");
            } else {
              System.out.println("FILETYPE UNKNOWN:" + text.node.fileType);
            }
          }
        }
      } else if (name.equals("close all")) {
        tabbedPane.removeAll();
      }
    }
  }
コード例 #9
0
 @SuppressWarnings("unchecked")
 private void exportBtnActionPerformed(java.awt.event.ActionEvent evt) {
   toggle(false);
   JFileChooser fc = new JFileChooser();
   String path =
       FileUtils.getUserDirectoryPath() + File.separator + treeViewNode.getText() + ".csv";
   fc.setSelectedFile(new File(path));
   fc.showSaveDialog(this);
   File target = fc.getSelectedFile();
   int row = model.getRowCount();
   try {
     boolean written;
     try (FileOutputStream fos = new FileOutputStream(target)) {
       while (--row > -1) {
         Vector v = (Vector) model.getDataVector().get(row);
         for (int i = 0; i < v.size(); i++) {
           if (v.get(i).toString().contains(",")) {
             v.set(i, ST.format("\"<%1>\"", v.get(i)));
           }
         }
         String line = ST.format("<%1:{ x |, <x>}>", v).substring(2);
         fos.write(line.getBytes(CHARSET));
         fos.write(Character.LINE_SEPARATOR);
       }
       written = true;
     }
     if (written) {
       LogEmitter.factory
           .get()
           .emit(
               this,
               Core.ALERT.INFO,
               ST.format("<%1> hosts written to <%2>", model.getRowCount(), target.getPath()));
     } else {
       LogEmitter.factory
           .get()
           .emit(this, Core.ALERT.DANGER, ST.format("Failed to export <%1>", target.getPath()));
     }
   } catch (FileNotFoundException ex) {
     Logger.getLogger(ConnectionDialog.class.getName()).log(Level.SEVERE, null, ex);
     LogEmitter.factory
         .get()
         .emit(this, Core.ALERT.DANGER, ST.format("Failed to export <%1>", target.getPath()));
   } catch (IOException ex) {
     Logger.getLogger(ConnectionDialog.class.getName()).log(Level.SEVERE, null, ex);
     LogEmitter.factory
         .get()
         .emit(this, Core.ALERT.DANGER, ST.format("Failed to export <%1>", target.getPath()));
   }
   toggle(true);
 }
コード例 #10
0
  public void createForm() {
    _nameLabel = new JLabel("Connection Name:");
    _usernameLabel = new JLabel("Username:"******"Password:"******"SVN URL:");
    _localLabel = new JLabel("Local Root:");

    _name = new JTextField(COLS);
    _name.setText(_workingCopy.getName());
    _username = new JTextField(COLS);
    _username.setText(_workingCopy.getUsername());
    _password = new JPasswordField(COLS);
    _password.setText(_workingCopy.getPassword());
    _url = new JTextField(COLS);
    _url.setText(_workingCopy.getUrl());

    _local = new JFileChooser();
    _local.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    _local.addActionListener(this);
    File current = new File(_workingCopy.getLocalRoot());
    _local.setSelectedFile(current);

    _error = new JLabel(" ");
    _error.setForeground(Color.red);

    _localButton = new JButton(".../" + current.getName());
    _localButton.addActionListener(this);

    _create = new JButton("Save Connection");
    _create.addActionListener(this);
    _cancel = new JButton("Cancel");
    _cancel.addActionListener(this);
    _test = new JButton("Test");
    _test.addActionListener(this);

    this.add(_nameLabel, "align right");
    this.add(_name);
    this.add(_usernameLabel, "align right");
    this.add(_username);
    this.add(_passwordLabel, "align right");
    this.add(_password);
    this.add(_urlLabel, "align right");
    this.add(_url);
    this.add(_localLabel, "align right");
    this.add(_localButton, "width 100%");
    this.add(_error, "span 2,align center");
    this.add(_cancel, "span 2, split 3, width 33%");
    this.add(_test, "width 33%");
    this.add(_create, "width 33%");
  }
コード例 #11
0
 // Get the name of the file
 private File getFileName(int option) {
   JFileChooser fc = new JFileChooser(new File(".."));
   if (oldFile != null) fc.setSelectedFile(oldFile);
   int returnVal = 0;
   if (option == UintahGui.OPEN) {
     returnVal = fc.showOpenDialog(UintahGui.this);
   } else {
     returnVal = fc.showSaveDialog(UintahGui.this);
   }
   if (returnVal == JFileChooser.APPROVE_OPTION) {
     File file = fc.getSelectedFile();
     oldFile = file;
     return file;
   } else return null;
 }
コード例 #12
0
 @Override
 public Component getTableCellEditorComponent(
     JTable table, Object value, boolean isSelected, int row, int column) {
   file = value.toString();
   SwingUtilities.invokeLater(
       () -> {
         fileChooser.setSelectedFile(new File(file));
         if (fileChooser.showOpenDialog(button) == JFileChooser.APPROVE_OPTION) {
           file = fileChooser.getSelectedFile().getAbsolutePath();
         }
         fireEditingStopped();
       });
   button.setText(file);
   return button;
 }
コード例 #13
0
  public void actionPerformed(ActionEvent e) {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle(toolTip);
    chooser.setDialogType(dialogType);
    chooser.setFileSelectionMode(fileSelectionMode);
    chooser.setSelectedFile(new File(textField.getText()));
    chooser.setFileFilter(preferredFileFilter);

    // if the user selects APPROVE then take the text
    if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
      // put the text in the text field
      String pathString = chooser.getSelectedFile().getAbsolutePath();
      textField.setText(pathString);
    }
  }
コード例 #14
0
 protected void fileSaveSimple() {
   JFileChooser chooser = null;
   if (currentFile == null) {
     chooser = new JFileChooser(startDirectory);
   } else {
     chooser = new JFileChooser(currentFile);
     if (!currentFile.isDirectory()) {
       chooser.setSelectedFile(currentFile);
     }
   }
   int returnVal = chooser.showSaveDialog(gw);
   if (returnVal == JFileChooser.APPROVE_OPTION) {
     currentFile = chooser.getSelectedFile();
     graph.saveSimple(currentFile);
   }
 }
コード例 #15
0
  public JFileChooser createFileChooser() {
    // create a filechooser
    JFileChooser fc = new JFileChooser();
    if (getSwingSet2() != null && getSwingSet2().isDragEnabled()) {
      fc.setDragEnabled(true);
    }

    // set the current directory to be the images directory
    File swingFile = new File("resources/images/About.jpg");
    if (swingFile.exists()) {
      fc.setCurrentDirectory(swingFile);
      fc.setSelectedFile(swingFile);
    }

    return fc;
  }
コード例 #16
0
  private void jButtonWorkingDirectoryBrowseActionPerformed(
      java.awt.event.ActionEvent
          evt) { // GEN-FIRST:event_jButtonWorkingDirectoryBrowseActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setMultiSelectionEnabled(false);

    String workDir = jTextWorkingDirectory.getText();
    if (workDir.equals("")) {
      workDir = FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath();
    }
    chooser.setSelectedFile(new File(workDir));
    chooser.setDialogTitle(
        NbBundle.getMessage(
            CustomizerRun.class, "LBL_CustomizeRun_Run_Working_Directory_Browse_Title")); // NOI18N
    if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) { // NOI18N
      File file = FileUtil.normalizeFile(chooser.getSelectedFile());
      jTextWorkingDirectory.setText(file.getAbsolutePath());
    }
  } // GEN-LAST:event_jButtonWorkingDirectoryBrowseActionPerformed
コード例 #17
0
ファイル: DecompileForm.java プロジェクト: albfan/jclazz
  private void saveToFile() {
    JFileChooser chooser = new JFileChooser();
    String saveName = clazz.getFileName();
    saveName = saveName.substring(0, saveName.lastIndexOf('.')) + ".java";
    chooser.setSelectedFile(new File(saveName));

    int returnVal = chooser.showSaveDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION) {
      JOptionPane.showMessageDialog(
          this, "No file specified", "Try again...", JOptionPane.WARNING_MESSAGE);
      return;
    }
    try {
      PrintWriter pw = new PrintWriter(new FileOutputStream(chooser.getSelectedFile()));
      pw.println(source);
      pw.close();
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(
          this, ioe.toString(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE);
      System.exit(1);
    }
  }
コード例 #18
0
  // Saves the open project to a new file selected by the user
  public boolean saveFileAs() {
    // Filter the file chooser by Cue Masher files
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new CueFileFilter());

    // Display the existing file location by default if it exists
    String filePath = soundManager.getProjectFilePath();
    if (filePath != null) {
      File openProjectFile = new File(filePath);
      fileChooser.setSelectedFile(openProjectFile);
    }

    int choice = fileChooser.showSaveDialog(CueMasherPanel.this);
    if (choice == JFileChooser.APPROVE_OPTION) {
      // Get the name of the file the user selected
      File file = fileChooser.getSelectedFile();
      filePath = file.getAbsolutePath().trim();

      // Make sure that it has a Cue Masher file extension
      String cueMasherExt = CueFileFilter.CUE_MASHER_FILE_EXT;
      boolean addExt = false;
      if (filePath.length() < cueMasherExt.length()) addExt = true;
      else {
        String ext =
            filePath.substring(filePath.length() - cueMasherExt.length(), filePath.length());
        if (!ext.equalsIgnoreCase(cueMasherExt)) addExt = true;
      }

      // Add the cue masher file extension if it doesn't exist
      if (addExt) filePath = filePath + cueMasherExt;

      // Save the project to the selected file
      soundManager.setProjectFilePath(filePath);
      return soundManager.saveFile();
    }
    return false;
  }
コード例 #19
0
  public static File startFileChooser(Component component, File selectedFile) {
    // Create a file chooser
    final JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setFileHidingEnabled(true);
    fc.setAcceptAllFileFilterUsed(false);
    if (selectedFile != null) fc.setSelectedFile(selectedFile);
    fc.setFileFilter(
        new FileFilter() {
          @Override
          public boolean accept(final File file) {
            if (file.isDirectory()) return true;
            String ext = Utils.getExtension(file);
            if (ext != null && ext.equals(Utils.XLS)) {
              return true;
            }
            return false;
          }

          @Override
          public String getDescription() {
            return "Excel *.xls";
          }
        });
    // In response to a button click:
    final int returnVal = fc.showOpenDialog(component);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();
      // This is where a real application would open the file.
      Log.d("Opening: " + file.getName() + ".");
      return file;
    } else {
      Log.d("Open command cancelled by user.");
    }
    return null;
  }
コード例 #20
0
  public void takeScreenshot(boolean flag) {
    BufferedImage bufferedimage;
    try {
      Robot robot = new Robot();
      Point point = getLocationOnScreen();
      Rectangle rectangle = new Rectangle(point.x, point.y, getWidth(), getHeight());
      bufferedimage = robot.createScreenCapture(rectangle);
    } catch (Throwable throwable) {
      JOptionPane.showMessageDialog(
          frame, "An error occured while trying to create a screenshot!", "Screenshot Error", 0);
      return;
    }
    String s = null;
    try {
      s = getNearestScreenshotFilename();
    } catch (IOException ioexception) {
      if (flag) {
        JOptionPane.showMessageDialog(
            frame,
            "A screenshot directory does not exist, and could not be created!",
            "No Screenshot Directory",
            0);
        return;
      }
    }
    if (s == null && flag) {
      JOptionPane.showMessageDialog(
          frame,
          "There are too many screenshots in the screenshot directory!\n"
              + "Delete some screen\n"
              + "shots and try again.",
          "Screenshot Directory Full",
          0);
      return;
    }
    if (!flag) {
      final JFileChooser fileChooser = new JFileChooser();
      final JDialog fileDialog = createFileChooserDialog(fileChooser, "Save Screenshot", this);
      final BufferedImage si = bufferedimage;
      JFileChooser _tmp = fileChooser;
      fileChooser.setFileSelectionMode(0);
      fileChooser.addChoosableFileFilter(new imageFileFilter());
      fileChooser.setCurrentDirectory(new File("C:/.hack3rClient/Scre/"));
      fileChooser.setSelectedFile(new File(s));
      JFileChooser _tmp1 = fileChooser;
      fileChooser.setDialogType(1);
      fileChooser.addActionListener(
          new ActionListener() {

            public void actionPerformed(ActionEvent actionevent) {
              String s1 = actionevent.getActionCommand();
              if (s1.equals("ApproveSelection")) {
                File file = fileChooser.getSelectedFile();
                if (file != null && file.isFile()) {
                  int i =
                      JOptionPane.showConfirmDialog(
                          frame,
                          (new StringBuilder())
                              .append(file.getAbsolutePath())
                              .append(" already exists.\n" + "Do you want to replace it?")
                              .toString(),
                          "Save Screenshot",
                          2);
                  if (i != 0) {
                    return;
                  }
                }
                try {
                  ImageIO.write(si, "png", file);
                  // client.pushMessage("Screenshot taken.", 3, "@cr2@ Client");
                  // JOptionPane.showMessageDialog(frame,"Screenshot Taken");
                } catch (IOException ioexception2) {
                  JOptionPane.showMessageDialog(
                      frame,
                      "An error occured while trying to save the screenshot!\n"
                          + "Please make sure you have\n"
                          + " write access to the screenshot directory.",
                      "Screenshot Error",
                      0);
                }
                fileDialog.dispose();
              } else if (s1.equals("CancelSelection")) {
                fileDialog.dispose();
              }
            }

            {
            }
          });
      fileDialog.setVisible(true);
    } else {
      try {
        ImageIO.write(
            bufferedimage,
            "png",
            new File((new StringBuilder()).append("C:/.hack3rClient/Scre/").append(s).toString()));
        JOptionPane.showMessageDialog(
            frame,
            "Image has been saved to C:/.hack3rclient/Scre. You can view your images by pushing File>View Images in the menu dropdowns.",
            "Screenshot manager",
            JOptionPane.INFORMATION_MESSAGE);
        // client.pushMessage("Screenshot taken.", 3, "@cr2@ Client");
        // JOptionPane.showMessageDialog(frame,"Screenshot taken.");
      } catch (IOException ioexception1) {
        JOptionPane.showMessageDialog(
            frame,
            "An error occured while trying to save the screenshot!\n"
                + "Please make sure you have\n"
                + " write access to the screenshot directory.",
            "Screenshot Error",
            0);
      }
    }
  }
コード例 #21
0
    public void actionPerformed(ActionEvent e) {
      if (isDirectorySelected()) {
        File dir = getDirectory();
        if (dir != null) {
          try {
            // Strip trailing ".."
            dir = ShellFolder.getNormalizedFile(dir);
          } catch (IOException ex) {
            // Ok, use f as is
          }
          changeDirectory(dir);
          return;
        }
      }

      JFileChooser chooser = getFileChooser();

      String filename = getFileName();
      FileSystemView fs = chooser.getFileSystemView();
      File dir = chooser.getCurrentDirectory();

      if (filename != null) {
        // Remove whitespaces from end of filename
        int i = filename.length() - 1;

        while (i >= 0 && filename.charAt(i) <= ' ') {
          i--;
        }

        filename = filename.substring(0, i + 1);
      }

      if (filename == null || filename.length() == 0) {
        // no file selected, multiple selection off, therefore cancel the approve action
        resetGlobFilter();
        return;
      }

      File selectedFile = null;
      File[] selectedFiles = null;

      // Unix: Resolve '~' to user's home directory
      if (File.separatorChar == '/') {
        if (filename.startsWith("~/")) {
          filename = System.getProperty("user.home") + filename.substring(1);
        } else if (filename.equals("~")) {
          filename = System.getProperty("user.home");
        }
      }

      if (chooser.isMultiSelectionEnabled()
          && filename.length() > 1
          && filename.charAt(0) == '"'
          && filename.charAt(filename.length() - 1) == '"') {
        List<File> fList = new ArrayList<File>();

        String[] files = filename.substring(1, filename.length() - 1).split("\" \"");
        // Optimize searching files by names in "children" array
        Arrays.sort(files);

        File[] children = null;
        int childIndex = 0;

        for (String str : files) {
          File file = fs.createFileObject(str);
          if (!file.isAbsolute()) {
            if (children == null) {
              children = fs.getFiles(dir, false);
              Arrays.sort(children);
            }
            for (int k = 0; k < children.length; k++) {
              int l = (childIndex + k) % children.length;
              if (children[l].getName().equals(str)) {
                file = children[l];
                childIndex = l + 1;
                break;
              }
            }
          }
          fList.add(file);
        }

        if (!fList.isEmpty()) {
          selectedFiles = fList.toArray(new File[fList.size()]);
        }
        resetGlobFilter();
      } else {
        selectedFile = fs.createFileObject(filename);
        if (!selectedFile.isAbsolute()) {
          selectedFile = fs.getChild(dir, filename);
        }
        // check for wildcard pattern
        FileFilter currentFilter = chooser.getFileFilter();
        if (!selectedFile.exists() && isGlobPattern(filename)) {
          changeDirectory(selectedFile.getParentFile());
          if (globFilter == null) {
            globFilter = new GlobFilter();
          }
          try {
            globFilter.setPattern(selectedFile.getName());
            if (!(currentFilter instanceof GlobFilter)) {
              actualFileFilter = currentFilter;
            }
            chooser.setFileFilter(null);
            chooser.setFileFilter(globFilter);
            return;
          } catch (PatternSyntaxException pse) {
            // Not a valid glob pattern. Abandon filter.
          }
        }

        resetGlobFilter();

        // Check for directory change action
        boolean isDir = (selectedFile != null && selectedFile.isDirectory());
        boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile));
        boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled();
        boolean isFileSelEnabled = chooser.isFileSelectionEnabled();
        boolean isCtrl =
            (e != null
                && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0);

        if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) {
          changeDirectory(selectedFile);
          return;
        } else if ((isDir || !isFileSelEnabled)
            && (!isDir || !isDirSelEnabled)
            && (!isDirSelEnabled || selectedFile.exists())) {
          selectedFile = null;
        }
      }

      if (selectedFiles != null || selectedFile != null) {
        if (selectedFiles != null || chooser.isMultiSelectionEnabled()) {
          if (selectedFiles == null) {
            selectedFiles = new File[] {selectedFile};
          }
          chooser.setSelectedFiles(selectedFiles);
          // Do it again. This is a fix for bug 4949273 to force the
          // selected value in case the ListSelectionModel clears it
          // for non-existing file names.
          chooser.setSelectedFiles(selectedFiles);
        } else {
          chooser.setSelectedFile(selectedFile);
        }
        chooser.approveSelection();
      } else {
        if (chooser.isMultiSelectionEnabled()) {
          chooser.setSelectedFiles(null);
        } else {
          chooser.setSelectedFile(null);
        }
        chooser.cancelSelection();
      }
    }
コード例 #22
0
  protected void filePNG() {

    JFileChooser chooser = null;
    File pngFile = null;
    if (currentFile == null) {
      chooser = new JFileChooser(startDirectory);
    } else {
      pngFile = new File(currentFile.getName() + ".png");
      chooser = new JFileChooser(pngFile);
      if (!currentFile.isDirectory()) {
        chooser.setSelectedFile(currentFile);
      }
    }

    if (pngFile == null) return;
    try {
      BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
      paint(image.getGraphics());
      ImageIO.write(image, "png", pngFile);
    } catch (Exception e) {
    }
    return;
    /*		JFileChooser chooser = null;
    		File pngFile = null;
    		if (currentFile == null) {
    			chooser = new JFileChooser(startDirectory);
    		} else {
    			pngFile = new File(currentFile.getName()+".png");
    			chooser = new JFileChooser(pngFile);
    			if (!currentFile.isDirectory()) {
    				chooser.setSelectedFile(currentFile);
    			}
    		}
    		int returnVal = chooser.showSaveDialog(gw);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			File pngFile = chooser.getSelectedFile();

    			int maxX = Integer.MIN_VALUE;
    			int minX = Integer.MAX_VALUE;
    			int maxY = Integer.MIN_VALUE;
    			int minY = Integer.MAX_VALUE;

    			while(Node node : getNodes()) {
    				if(node.getX() > maxX) {
    					maxX = node.getX();
    				}
    				if(node.getX() < minX) {
    					minX = node.getX();
    				}
    				if(node.getY() > maxY) {
    					maxY = node.getY();
    				}
    				if(node.getY() < minY) {
    					minY = node.getY();
    				}
    			}

    			BufferedImage image = new BufferedImage(maxX-minX+50,maxY-minY+50,BufferedImage.TYPE_INT_RGB);



    			ImageIO.write(image,"png",pngFile);
    		}
    */ }
コード例 #23
0
 public void setSourceName(String name) {
   sourceFileChooser.setName(name);
   sourceFileChooser.setSelectedFile(new File(name));
 }
コード例 #24
0
  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == open) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.setFileFilter(new InputFileFilter(false));
      if (loadedFile != null) chooser.setSelectedFile(loadedFile);
      int returnValue = chooser.showOpenDialog(this);
      if (returnValue == JFileChooser.APPROVE_OPTION) {
        boolean approved =
            ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile());
        if (approved) {
          startProgress();
          new MultiThread(
                  new Runnable() {
                    public void run() {
                      try {

                        loadedFile = chooser.getSelectedFile();
                        FileInputStream fis = new FileInputStream(loadedFile);
                        InputParser ip = new InputParser(fis);
                        if (ip.parseInput()) {
                          field = new Field(new ArrayList<Point>(Arrays.asList(ip.getPoints())));
                          minAlgo.setText(String.valueOf(ip.minimumClusters));
                          maxAlgo.setText(String.valueOf(ip.maximumClusters));
                        }
                      } catch (FileNotFoundException e1) {
                      }
                      contentpanel.center();
                      stopProgress();
                    }
                  })
              .start();
        }
      }
    } else if (e.getSource() == center) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      startProgress();
      new MultiThread(
              new Runnable() {
                public void run() {
                  contentpanel.removeMouseWheelListener(contentpanel);
                  contentpanel.center();
                  contentpanel.addMouseWheelListener(contentpanel);
                  stopProgressRepaint();
                }
              })
          .start();
    } else if (e.getSource() == save) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.setFileFilter(new InputFileFilter(true));
      if (loadedFile != null) chooser.setSelectedFile(loadedFile);
      int returnValue = chooser.showSaveDialog(this);
      if (returnValue == JFileChooser.APPROVE_OPTION) {
        boolean approved =
            ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile());
        if (approved) {
          loadedFile = chooser.getSelectedFile();
          boolean halt = loadedFile.exists();
          if (halt) {
            int i =
                JOptionPane.showInternalConfirmDialog(
                    c,
                    "Are you sure you want to override this file?",
                    "Warning",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
            if (i == JOptionPane.YES_OPTION) {
              halt = false;
            }
          }

          if (!halt) {
            try {
              PrintWriter pw = new PrintWriter(new FileWriter(loadedFile));
              pw.println("find " + field.getNumberOfClusters() + " clusters");
              pw.println(field.size() + " points");
              Object[] obj = field.toArray();
              for (int i = 0; i < obj.length; i++) {
                Point p = (Point) obj[i];
                pw.println(p.getX() + " " + p.getY());
              }
              pw.close();
            } catch (IOException e1) {
            }
          }
        }
      }
    } else if (e.getSource() == clear) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      int i =
          JOptionPane.showInternalConfirmDialog(
              c,
              "Are you sure you want to clear the field?",
              "Warning",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.WARNING_MESSAGE);

      checkRunned();
      if (i == JOptionPane.YES_OPTION) {
        field = new Field();
        updateContentPanel();
      }
    } else if (e.getSource() == circle) {
      contentpanel.setSelectionMode(ContentPanel.SELECT_CIRCLE);
    } else if (e.getSource() == square) {
      contentpanel.setSelectionMode(ContentPanel.SELECT_SQUARE);
    } else if (e.getSource() == addacluster) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      contentpanel.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    } else if (e.getSource() == addnoise) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();
      final String s =
          JOptionPane.showInternalInputDialog(
              c, "How many points?", "Add noise", JOptionPane.QUESTION_MESSAGE);

      startProgress();
      new MultiThread(
              new Runnable() {
                public void run() {
                  if (s != null) {
                    int number;
                    try {
                      number = Integer.parseInt(s);
                    } catch (Exception ex) {
                      number = 0;
                    }

                    int tillX = 1000000000;
                    int tillY = 1000000000;
                    int addX = 0;
                    int addY = 0;
                    if (inRectangle.isSelected()) {
                      Rectangle r = field.getBoundingRectangle();
                      if (!(r.x1 == 0 && r.y1 == 0 && r.x2 == 0 && r.y2 == 0)) {
                        tillX = r.x2 - r.x1;
                        addX = r.x1;
                        tillY = r.y2 - r.y1;
                        addY = r.y1;
                      } else {
                        tillX = 500000000;
                        tillY = 500000000;
                      }
                    }

                    for (int i = 0; i < number; i++) {
                      int x = random.nextInt(tillX);
                      x += addX;
                      int y;

                      boolean busy = true;
                      while (busy) {
                        y = random.nextInt(tillY);
                        y += addY;
                        boolean inside = false;
                        Object[] array = field.toArray();
                        for (int j = 0; j < field.size(); j++) {
                          if (((Point) array[j]).compareTo(x, y)) {
                            inside = true;
                            break;
                          }
                        }

                        if (!inside) {
                          field.add(new Point(x, y));
                          busy = false;
                        }
                      }
                    }
                  }
                  stopProgress();
                }
              })
          .start();
    } else if (e.getSource() == run) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      startProgress();

      runAlgo();
    }
  }
コード例 #25
0
    @Override
    public void actionPerformed(ActionEvent evt) {
      String command = evt.getActionCommand();
      switch (command) {
        case "New File":
          {
            OSC = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics osg = OSC.getGraphics();
            osg.setColor(fillColor);
            osg.fillRect(0, 0, getWidth(), getHeight());
            osg.dispose();
            repaint();
            break;
          }
        case "Open":
          {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter =
                new FileNameExtensionFilter("JPG or PNG Images", "jpg", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
              try {

                OSC = ImageIO.read(chooser.getSelectedFile());
                Graphics2D g2 = (Graphics2D) OSC.getGraphics();

                g2.scale((double) 640 / OSC.getWidth(), (double) 480 / OSC.getHeight());
                g2.drawImage(OSC, 0, 0, OSC.getWidth(), OSC.getHeight(), null);
              } catch (Exception e) {
              }
            }
            repaint();
            break;
          }
        case "Save":
          {
            JFileChooser fileDialog = new JFileChooser();
            fileDialog.setSelectedFile(new File("image.PNG"));
            fileDialog.setDialogTitle("Select File to be Saved");
            int option = fileDialog.showSaveDialog(null);
            if (option != JFileChooser.APPROVE_OPTION)
              return; // User canceled or clicked the dialog’s close box.

            File selectedFile = fileDialog.getSelectedFile();
            if (selectedFile.exists()) { // Ask the user whether to replace the file.
              int response =
                  JOptionPane.showConfirmDialog(
                      null,
                      "The file \""
                          + selectedFile.getName()
                          + "\" already exists.\nDo you want to replace it?",
                      "Confirm Save",
                      JOptionPane.YES_NO_OPTION,
                      JOptionPane.WARNING_MESSAGE);
              if (response != JOptionPane.YES_OPTION)
                return; // User does not want to replace the file.
            }
            try {
              boolean hasFormat = ImageIO.write(OSC, "PNG", selectedFile);
              if (!hasFormat) throw new Exception("PNG" + " format is not available.");
            } catch (Exception e) {
              JOptionPane.showMessageDialog(
                  null, "Sorry, an error occurred while trying to save image.");
              e.printStackTrace();
            }

            break;
          }
        case "Exit":
          {
            System.exit(0);
          }

        case "Select Drawing Color...":
          {
            Color newColor =
                JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Drawing Color", currentColor);
            if (newColor != null) currentColor = newColor;
            break;
          }
        case "Fill With Color...":
          {
            Color newColor =
                JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Fill Color", fillColor);
            if (newColor != null) {
              fillColor = newColor;
              Graphics osg = OSC.getGraphics();
              osg.setColor(fillColor);
              osg.fillRect(0, 0, OSC.getWidth(), OSC.getHeight());
              osg.dispose();
              AdvancedGUIEX1.this.repaint();
            }
            break;
          }
        case "Draw With Black":
          currentColor = Color.BLACK;
          break;
        case "Draw With White":
          currentColor = Color.WHITE;
          break;
        case "Draw With Red":
          currentColor = Color.RED;
          break;
        case "Draw With Green":
          currentColor = Color.GREEN;
          break;
        case "Draw With Blue":
          currentColor = Color.BLUE;
          break;
        case "Draw With Yellow":
          currentColor = Color.YELLOW;
          break;
        case "Curve":
          currentTool = Tool.CURVE;
          break;
        case "Line":
          currentTool = Tool.LINE;
          break;
        case "Rectangle":
          currentTool = Tool.RECT;
          break;
        case "Oval":
          currentTool = Tool.OVAL;
          break;
        case "Filled Rectangle":
          currentTool = Tool.FILLED_RECT;
          break;
        case "Filled Oval":
          currentTool = Tool.FILLED_OVAL;
          break;
        case "Smudge":
          currentTool = Tool.SMUDGE;
          break;
        case "Erase":
          currentTool = Tool.ERASE;
          break;
      }
    }
コード例 #26
0
 public void setDestinationName(String name) {
   destFileChooser.setName(name);
   destFileChooser.setSelectedFile(new File(name));
 }