Пример #1
0
  public void cargarImgen(int valor) {
    try {
      fc = new JFileChooser();
      fc.setAcceptAllFileFilterUsed(false); // No deja seleccionar todo tipo de archivos
      FileNameExtensionFilter filtroImagen =
          new FileNameExtensionFilter(
              "Imágenes JPG, PNG & GIF", "jpg", "png", "gif"); // Creo filtro para tipo de imagen
      fc.addChoosableFileFilter(filtroImagen); // Asigno el filtro creado de imagenes

      int returnVal = fc.showOpenDialog(this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {

        String path = this.getClass().getResource("Imagenes").getPath();

        File file = fc.getSelectedFile();

        String extension = file.getName().substring((file.getName().lastIndexOf(".") + 1));
        // Si el valor es 1 es un producto individual
        if (valor == 1) {
          userImgName = path + "\\Prod-Ind-" + txtNombre.getText() + "." + extension;
        } else {
          userImgName = path + "\\Prod-Prom-" + txtNomProm.getText() + "." + extension;
        }
        File fileToSave = new File(userImgName);
        FileWriter fileWr = new FileWriter(fileToSave);
        fileWr.close();
        Files.copy(
            fc.getSelectedFile().toPath(),
            fileToSave.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
      }

    } catch (HeadlessException | IOException ex) {
      JOptionPane.showMessageDialog(
          this, "Error al cargar imagen", "Error", JOptionPane.ERROR_MESSAGE);
      System.out.println("Error en alta cliente: " + ex.getMessage());
    }
  }