下面列出了java.awt.Desktop#open ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
@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());
}
}
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;
}
}
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;
}
}
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);
}
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);
}
}
};
}
/**
* 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;
}
}
}
/**
* 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;
}
}
}
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);
}
}
}
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);
}
}
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();
}
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();
}
/**
* @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);
}
}
@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();
}
}
/**
* 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());
}
}
/**
* 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());
}
}
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);
}
}
}
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();
}
}
/**
* @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);
}
}
public static void openFile( File file ) throws IOException {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
}
}