Java Code Examples for java.awt.Desktop#open()

The following examples show how to use java.awt.Desktop#open() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShowLibraryFolderCommand.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
    try {
        File    dir     = mLibrary.getPath().toFile();
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Action.BROWSE_FILE_DIR)) {
            File[] contents = dir.listFiles();
            if (contents != null && contents.length > 0) {
                Arrays.sort(contents);
                dir = contents[0];
            }
            desktop.browseFileDirectory(dir.getCanonicalFile());
        } else {
            desktop.open(dir);
        }
    } catch (Exception exception) {
        WindowUtils.showError(null, exception.getMessage());
    }
}
 
Example 2
Source File: LinkBrowser.java    From launcher with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static boolean attemptDesktopOpen(String directory)
{
	if (!Desktop.isDesktopSupported())
	{
		return false;
	}

	final Desktop desktop = Desktop.getDesktop();

	if (!desktop.isSupported(Desktop.Action.OPEN))
	{
		return false;
	}

	try
	{
		desktop.open(new File(directory));
		return true;
	}
	catch (IOException ex)
	{
		log.warn("Failed to open Desktop#open {}", directory, ex);
		return false;
	}
}
 
Example 3
Source File: DesktopNetworkBridge.java    From CrossMobile with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@SuppressWarnings({"UseSpecificCatch"})
public boolean openURL(String url) {
    Desktop desktop = Desktop.getDesktop();
    try {
        URI uri = URI.create(url);
        if (url.startsWith("mailto:"))
            desktop.mail(uri);
        else
            desktop.browse(uri);
    } catch (Exception ex) {
        try {
            desktop.open(new File(url));
        } catch (Exception ex1) {
            Native.system().error("Unable to open URL " + url, ex);
            return false;
        }
    }
    return true;
}
 
Example 4
Source File: LinkBrowser.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static boolean attemptDesktopOpen(String directory)
{
	if (!Desktop.isDesktopSupported())
	{
		return false;
	}

	final Desktop desktop = Desktop.getDesktop();

	if (!desktop.isSupported(Desktop.Action.OPEN))
	{
		return false;
	}

	try
	{
		desktop.open(new File(directory));
		return true;
	}
	catch (IOException ex)
	{
		log.warn("Failed to open Desktop#open {}", directory, ex);
		return false;
	}
}
 
Example 5
Source File: DesktopUtil.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
public static void open(final String filename, final Program program) {
	File file = new File(filename);
	LOG.info("Opening: {}", file.getName());
	if (isSupported(Desktop.Action.OPEN)) {
		Desktop desktop = Desktop.getDesktop();
		try {
			desktop.open(file);
			return;
		} catch (IOException ex) {
			LOG.warn("	Opening Failed: {}", ex.getMessage());
		}
	} else {
		LOG.warn("	Opening failed");
	}
	JOptionPane.showMessageDialog(program.getMainWindow().getFrame(), "Could not open " + file.getName(), "Open File", JOptionPane.PLAIN_MESSAGE);
}
 
Example 6
Source File: Utils.java    From aurous-app with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Open a file using {@link Desktop} if supported, or a manual
 * platform-specific method if not.
 *
 * @param file
 *            The file to open.
 * @throws Exception
 *             if the file could not be opened.
 */
public static void openFile(final File file) throws Exception {
	final Desktop desktop = Desktop.isDesktopSupported() ? Desktop
			.getDesktop() : null;
			if ((desktop != null) && desktop.isSupported(Desktop.Action.OPEN)) {
				desktop.open(file);
			} else {
				final OperatingSystem system = Utils.getPlatform();
				switch (system) {
				case MAC:
				case WINDOWS:
					Utils.openURL(file.toURI().toURL());
					break;
				default:
					final String fileManager = Utils.findSupportedProgram(
							"file manager", Utils.FILE_MANAGERS);
					Runtime.getRuntime().exec(
							new String[] { fileManager, file.getAbsolutePath() });
					break;
				}
			}
}
 
Example 7
Source File: Utils.java    From aurous-app with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Open a file using {@link Desktop} if supported, or a manual
 * platform-specific method if not.
 *
 * @param file
 *            The file to open.
 * @throws Exception
 *             if the file could not be opened.
 */
public static void openFile(final File file) throws Exception {
	final Desktop desktop = Desktop.isDesktopSupported() ? Desktop
			.getDesktop() : null;
	if ((desktop != null) && desktop.isSupported(Desktop.Action.OPEN)) {
		desktop.open(file);
	} else {
		final OperatingSystem system = Utils.getPlatform();
		switch (system) {
		case MAC:
		case WINDOWS:
			Utils.openURL(file.toURI().toURL());
			break;
		default:
			final String fileManager = Utils.findSupportedProgram(
					"file manager", Utils.FILE_MANAGERS);
			Runtime.getRuntime().exec(
					new String[] { fileManager, file.getAbsolutePath() });
			break;
		}
	}
}
 
Example 8
Source File: Utils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
static Runnable createLinkRunnable(final Path path) {
    return new Runnable () {
        @Override
        public void run () {
            File file = path.toFile();
            if (!file.exists()) {
                LOGGER.info("file does not exist: " + file);
                return;
            }

            Desktop dt = Desktop.getDesktop();
            try {
                dt.open(file);
            } catch (IOException ex) {
                LOGGER.log(Level.WARNING, "can't open path", ex);
            }
        }
    };
}
 
Example 9
Source File: SystemUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
public static void open(byte[] data, String extension) {
	if (data != null && Desktop.isDesktopSupported()) {
		Desktop desktop = Desktop.getDesktop();
		File file;
		try {
			file = File.createTempFile("tmp", "." + extension);
			file.deleteOnExit();
			FileUtils.writeByteArrayToFile(file, data);
			desktop.open(file);
		} catch (IOException e) {
			String message = "No ha sido posible abrir el fichero";
			JOptionPane.showMessageDialog(null, message, "Error de datos", JOptionPane.ERROR_MESSAGE);
		}
	}
}
 
Example 10
Source File: ReceiveFileTransfer.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Launches a file browser or opens a file with java Desktop.open() if is
 * supported
 * 
 * @param file
 */
private void launchFile(File file) {
    if (!Desktop.isDesktopSupported())
        return;
    Desktop dt = Desktop.getDesktop();
    try {
        dt.open(file);
    } catch (IOException ex) {
        launchFile(file.getPath());
    }
}
 
Example 11
Source File: SparkTransferManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Launches a file browser or opens a file with java Desktop.open() if is
 * supported
 * 
 * @param file
 */
private void launchFile(File file) {
    if (!Desktop.isDesktopSupported())
        return;
    Desktop dt = Desktop.getDesktop();
    try {
        dt.open(file);
    } catch (IOException ex) {
        launchFile(file.getPath());
    }
}
 
Example 12
Source File: CameraTest.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPictureTaken( String fileWritten ) {
    System.out.println("Written: " + fileWritten);
    Desktop desktop = Desktop.getDesktop();
    try {
        desktop.open(new File(fileWritten));
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 13
Source File: UpdateCheck.java    From Shuffle-Move with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param file
 *           The file to show the folder of.
 */
public void showParentOf(File file) {
   Desktop d = Desktop.getDesktop();
   try {
      d.open(file.getParentFile());
   } catch (IOException e) {
      String message = getString(KEY_GET_IOEXCEPTION_OPEN, file.getAbsolutePath());
      LOG.log(Level.SEVERE, message, e);
   }
}
 
Example 14
Source File: NbUtils.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
public static void openInSystemViewer (@Nullable final Component parentComponent, @Nonnull final File file) {
  final Runnable startEdit = new Runnable() {
    @Override
    public void run () {
      boolean ok = false;
      if (Desktop.isDesktopSupported()) {
        final Desktop dsk = Desktop.getDesktop();
        if (dsk.isSupported(Desktop.Action.OPEN)) {
          try {
            dsk.open(file);
            ok = true;
          }
          catch (Throwable ex) {
            LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
          }
        }
      }
      if (!ok) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run () {
            NbUtils.msgError(parentComponent, "Can't open file in system viewer! See the log!");//NOI18N
            Toolkit.getDefaultToolkit().beep();
          }
        });
      }
    }
  };
  final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
  thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException (final Thread t, final Throwable e) {
      LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
    }
  });

  thr.setDaemon(true);
  thr.start();
}
 
Example 15
Source File: UiUtils.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
public static void openInSystemViewer(@Nonnull final File file) {
  final Runnable startEdit = () -> {
    boolean ok = false;
    if (Desktop.isDesktopSupported()) {
      final Desktop dsk = Desktop.getDesktop();
      if (dsk.isSupported(Desktop.Action.OPEN)) {
        try {
          dsk.open(file);
          ok = true;
        } catch (Throwable ex) {
          LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N //NOI18N
        }
      }
    }
    if (!ok) {
      SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          DialogProviderManager.getInstance().getDialogProvider().msgError(Main.getApplicationFrame(), "Can't open file in system viewer! See the log!");//NOI18N
          Toolkit.getDefaultToolkit().beep();
        }
      });
    }
  };
  final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
  thr.setUncaughtExceptionHandler((final Thread t, final Throwable e) -> {
    LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e); //NOI18N
  });

  thr.setDaemon(true);
  thr.start();
}
 
Example 16
Source File: LibraryAssistantUtil.java    From Library-Assistant with Apache License 2.0 5 votes vote down vote up
public static void openFileWithDesktop(File file) {
    try {
        Desktop desktop = Desktop.getDesktop();
        desktop.open(file);
    } catch (IOException ex) {
        Logger.getLogger(LibraryAssistantUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 17
Source File: PayloadMenu.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static void openFile( String fileName){
   if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();
      try {
         fileName = fileName.replace('\\', '/');
         File f = new File(fileName);
         if (f.exists()) {
            desktop.open(f);
         }
      } catch (IOException e) {
         ExceptionHandler.handle(e);
      }
   }
}
 
Example 18
Source File: GuiUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static void openFile( File file ) throws IOException {
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        desktop.open(file);
    }
}
 
Example 19
Source File: GridPanel.java    From Shuffle-Move with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param shuffleController
 */
public static void printGrid(GridPrintConfigServiceUser user) {
   SimulationResult simResult = user.getSelectedResult();
   List<Integer> move = new ArrayList<Integer>();
   List<Integer> pickup = new ArrayList<Integer>();
   List<Integer> dropat = new ArrayList<Integer>();
   if (simResult != null) {
      move = simResult.getMove();
      if (move.size() >= 2) {
         pickup.addAll(move.subList(0, 2));
         if (move.size() >= 4) {
            dropat.addAll(move.subList(2, 4));
         }
      }
   }
   
   ConfigManager preferencesManager = user.getPreferencesManager();
   ImageManager imageManager = user.getImageManager();
   
   boolean includeCursor = preferencesManager.getBooleanValue(KEY_PRINT_INCLUDE_CURSOR,
         DEFAULT_PRINT_INCLUDE_CURSOR);
   boolean includeMove = preferencesManager.getBooleanValue(KEY_PRINT_INCLUDE_MOVE, DEFAULT_PRINT_INCLUDE_MOVE);
   boolean includeGrid = preferencesManager.getBooleanValue(KEY_PRINT_INCLUDE_GRID, DEFAULT_PRINT_INCLUDE_GRID);
   
   List<Integer> curCursor = user.getCurrentCursor();
   List<Integer> prevCursor = user.getPreviousCursor();
   
   int innerBorderThick = includeCursor ? getCellBorderInnerThickness(user) : 0;
   int outerBorderThick = includeGrid ? getCellOutlineThickness(user) : 0;
   int borderThick = innerBorderThick + outerBorderThick;
   int iconWidth = imageManager.getIconWidth();
   int iconHeight = imageManager.getIconHeight();
   int cellWidth = iconWidth + borderThick * 2;
   int cellHeight = iconHeight + borderThick * 2;
   
   BufferedImage result = new BufferedImage(Board.NUM_COLS * cellWidth, Board.NUM_ROWS * cellHeight,
         BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = result.createGraphics();
   g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   
   for (int pos = 1; pos <= Board.NUM_CELLS; pos++) {
      // Coordinates in the grid (row, column) where each starts at 1
      List<Integer> coords = ShuffleModel.getCoordsFromPosition(pos);
      // start point for this cell's pixel coordinates
      int cellPixelX = (coords.get(1) - 1) * cellWidth;
      int cellPixelY = (coords.get(0) - 1) * cellHeight;
      if (includeMove) {
         // The background fill for move selection
         Color moveColor = getMoveColorFor(coords, pickup, dropat, preferencesManager);
         if (moveColor != null) {
            g.setPaint(moveColor);
            g.fillRect(cellPixelX, cellPixelY, cellWidth, cellHeight);
         }
      }
      if (includeCursor) {
         // the selection cursor
         Color thisCursorColor = getCursorColor(coords, curCursor, prevCursor, preferencesManager);
         if (thisCursorColor != null) {
            g.setPaint(thisCursorColor);
            drawBorder(g, cellPixelX + outerBorderThick, cellPixelY + outerBorderThick,
                  iconWidth + 2 * innerBorderThick, iconHeight + 2 * innerBorderThick, innerBorderThick);
         }
      }
      // The icon itself
      SpeciesPaint s = user.getPaintAt(coords.get(0), coords.get(1));
      Image img = imageManager.getImageFor(s).getImage();
      int iconPixelX = cellPixelX + borderThick;
      int iconPixelY = cellPixelY + borderThick;
      g.drawImage(img, iconPixelX, iconPixelY, iconWidth, iconHeight, null);
      if (includeGrid) {
         // The grey grid outline
         g.setPaint(Color.gray);
         drawBorder(g, cellPixelX, cellPixelY, cellWidth, cellHeight, outerBorderThick);
      }
   }
   g.dispose();
   
   try {
      File outputFile = getGridConfigFile(user);
      ImageIO.write(result, "png", outputFile);
      Desktop desktop = Desktop.getDesktop();
      desktop.open(outputFile);
   } catch (Exception e) {
      LOG.log(Level.SEVERE, e.getMessage(), e);
   }
}
 
Example 20
Source File: IdeaUtils.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
public static void openInSystemViewer(@Nonnull final DialogProvider dialogProvider, @Nullable final VirtualFile theFile) {
  final File file = vfile2iofile(theFile);

  if (file == null) {
    LOGGER.error("Can't find file to open, null provided");
    dialogProvider.msgError(null, "Can't find file to open");
  } else {
    final Runnable startEdit = new Runnable() {
      @Override
      public void run() {
        boolean ok = false;
        if (Desktop.isDesktopSupported()) {
          final Desktop dsk = Desktop.getDesktop();
          if (dsk.isSupported(Desktop.Action.OPEN)) {
            try {
              dsk.open(file);
              ok = true;
            } catch (Throwable ex) {
              LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
            }
          }
        }
        if (!ok) {
          SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
              dialogProvider.msgError(null, "Can't open file in system viewer! See the log!");//NOI18N
              Toolkit.getDefaultToolkit().beep();
            }
          });
        }
      }
    };
    final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
    thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(final Thread t, final Throwable e) {
        LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
      }
    });

    thr.setDaemon(true);
    thr.start();
  }
}