下面列出了怎么用java.awt.Desktop的API类实例代码及写法,或者点击链接到github查看源代码。
public static void save(ActionEvent e, CycleView graph) {
int w = graph.getWidth();
int h = graph.getHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
graph.paint(img.createGraphics());
JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.home")));
int c = chooser.showSaveDialog(graph);
if (c == JFileChooser.CANCEL_OPTION) {
System.out.println("cancel");
return;
}
try {
File f = chooser.getSelectedFile();
ImageIO.write(img, "png", f);
System.out.println(f.getAbsolutePath());
Desktop.getDesktop().open(f.getParentFile());
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void selectItem(String item, Graph graph, GraphElementType elementType, int elementId, Vector3f unprojected) {
final ReadableGraph rg = graph.getReadableGraph();
try {
final int attribute = rg.getAttribute(elementType, item);
if (attribute != Graph.NOT_FOUND) {
final URI uri = (URI) rg.getObjectValue(attribute, elementId);
if (uri != null) {
Desktop.getDesktop().browse(uri);
// unable to use the plugin due to a circular dependency
// PluginExecution.withPlugin(VisualGraphPluginRegistry.OPEN_IN_BROWSER)
// .withParameter(OpenInBrowserPlugin.APPLICATION_PARAMETER_ID, "Browse To")
// .withParameter(OpenInBrowserPlugin.URL_PARAMETER_ID, uri)
// .executeLater(null);
}
}
} catch (IOException ex) {
} finally {
rg.release();
}
}
public static boolean navigateUrl(String url) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
try {
URI uri = new URI(url);
desktop.browse(uri);
return true;
} catch (URISyntaxException | IOException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return false;
}
private JPopupMenu createHelpMenu() {
final JPopupMenu jsMenu = new JPopupMenu();
final String[][] entries = new String[][]{
{"BEAM JavaScript (BEAM Wiki)", "http://www.brockmann-consult.de/beam-wiki/display/BEAM/BEAM+JavaScript+Examples"},
{"JavaScript Introduction (Mozilla)", "http://developer.mozilla.org/en/docs/JavaScript"},
{"JavaScript Syntax (Wikipedia)", "http://en.wikipedia.org/wiki/JavaScript_syntax"},
};
for (final String[] entry : entries) {
final String text = entry[0];
final String target = entry[1];
final JMenuItem menuItem = new JMenuItem(text);
menuItem.addActionListener(e -> {
try {
Desktop.getDesktop().browse(new URI(target));
} catch (IOException | URISyntaxException e1) {
getScriptConsoleTopComponent().showErrorMessage(e1.getMessage());
}
});
jsMenu.add(menuItem);
}
return jsMenu;
}
private void jLabel_webMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_webMouseClicked
// TODO add your handling code here:
try {
URI uri = new URI("http://www.meteothink.org");
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null) {
desktop.browse(uri);
}
} catch (URISyntaxException ex) {
Logger.getLogger(FrmAbout.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ioe) {
}
}
private void logoutDesktop() throws IOException, URISyntaxException, InterruptedException {
CallbackListener callback = new CallbackListener();
callback.start();
String redirectUri = "http://localhost:" + callback.getLocalPort();
String logoutUrl = deployment.getLogoutUrl()
.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
.build().toString();
Desktop.getDesktop().browse(new URI(logoutUrl));
try {
callback.await();
} catch (InterruptedException e) {
callback.stop();
throw e;
}
}
private void jLabel_webMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_webMouseClicked
// TODO add your handling code here:
try {
URI uri = new URI("http://www.meteothink.org");
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null) {
desktop.browse(uri);
}
} catch (URISyntaxException ex) {
Logger.getLogger(FrmAbout.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ioe) {
}
}
private void attemptOpenBrowser() {
String targetURL = SysConstants.WEBSITE_URL;
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop()
: null;
if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
JOptionPane
.showMessageDialog(
this,
"The downloads page could not be opened automatically.\n"
+ "Open a browser and navigate to the below link to download the update:\n"
+ targetURL);
} else {
try {
desktop.browse(new URI(targetURL));
} catch (Exception e) {
JOptionPane
.showMessageDialog(
this,
"The downloads page could not be opened automatically.\n"
+ "Open a browser and navigate to the below link to download the update:\n"
+ targetURL);
}
}
this.setVisible(false);
}
private static boolean editDESKTOP(File file) {
logOut("Trying to use Desktop.getDesktop().edit() with " + file);
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
logErr("EDIT is not supported.");
return false;
}
Desktop.getDesktop().edit(file);
return true;
} catch (Throwable t) {
logErr("Error using desktop edit.", t);
return false;
}
}
/**
* 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;
}
}
}
/**
* Applies a quit handler which will close the given tool.
*
* @param tool The tool to close, which should result in the desired quit behavior.
*/
public static synchronized void install(PluginTool tool) {
if (installed) {
return;
}
installed = true;
if (Platform.CURRENT_PLATFORM.getOperatingSystem() != OperatingSystem.MAC_OS_X) {
return;
}
Desktop.getDesktop().setQuitHandler((evt, response) -> {
response.cancelQuit(); // allow our tool to quit the application instead of the OS
tool.close();
});
}
public AddPropertiesView(TestPropertiesInfo issueInfo) {
this.issueInfo = issueInfo;
initComponents();
// @formatter:off
Label severityLabel = new Label("Severity: ");
severityLabel.setMinWidth(Region.USE_PREF_SIZE);
tmsLink.setOnAction((e) -> {
try {
Desktop.getDesktop().browse(new URI(tmsLink.getText()));
} catch (Exception e1) {
FXUIUtils._showMessageDialog(null, "Unable to open link: " + tmsLink.getText(), "Unable to open link",
AlertType.ERROR);
e1.printStackTrace();
}
});
formPane.addFormField("Name: ", nameField)
.addFormField("Description: ", descriptionField)
.addFormField("ID: ", idField, severityLabel, severities);
String tmsPattern = System.getProperty(Constants.PROP_TMS_PATTERN);
if (tmsPattern != null && tmsPattern.length() > 0) {
tmsLink.textProperty().bind(Bindings.format(tmsPattern, idField.textProperty()));
formPane.addFormField("", tmsLink);
}
// @formatter:on
setCenter(content);
}
public ResultsTextPane(StyledDocument doc) {
super(doc);
createStyles();
setEditorKit(JTextPane.createEditorKitForContentType("text/html"));
setEditable(false);
addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
}
}
});
}
/**
* View a URI in a browser.
*
* @param uri URI to display in browser.
* @throws IOException if browser can not be launched
*/
private static void viewInBrowser(URI uri) throws IOException
{
if (Desktop.isDesktopSupported() && DESKTOP.isSupported(Action.BROWSE))
{
DESKTOP.browse(uri);
}
else
{
Dialog<ButtonType> alert = GuiUtility.runOnJavaFXThreadNow(() -> new Alert(Alert.AlertType.WARNING));
Logging.debugPrint("unable to browse to " + uri);
alert.setTitle(LanguageBundle.getString("in_err_browser_err"));
alert.setContentText(LanguageBundle.getFormattedString("in_err_browser_uri", uri));
GuiUtility.runOnJavaFXThreadNow(alert::showAndWait);
}
}
private static boolean openDESKTOP(File file) {
logOut("Trying to use Desktop.getDesktop().open() with " + file.toString());
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
logErr("OPEN is not supported.");
return false;
}
Desktop.getDesktop().open(file);
return true;
} catch (Throwable t) {
logErr("Error using desktop open.", t);
return false;
}
}
private static boolean browseDESKTOP(URI uri) {
logOut("Trying to use Desktop.getDesktop().browse() with " + uri.toString());
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
logErr("BROWSE is not supported.");
return false;
}
Desktop.getDesktop().browse(uri);
return true;
} catch (Throwable t) {
logErr("Error using desktop browse.", t);
return false;
}
}
private String getAuthCode()
throws IOException, InterruptedException
{
URI uri = authCodeUriRequest.execute();
if (Desktop.isDesktopSupported() &&
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE))
{
Desktop.getDesktop().browse(uri);
}
AuthCallbackServer server = new AuthCallbackServer();
while (server.getAccessToken() == null)
{
Thread.sleep(1000);
}
if (!server.getAccessToken().equals("error"))
{
startRefreshTokenTimer();
}
stopServer(server);
return server.getAccessToken();
}
public static boolean open(String url) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(new URL(url).toURI());
return true;
}
catch (Exception e) {
e.printStackTrace();
}
}
JFrame frame = new JFrame("Help");
JLabel lbl = new JLabel(url);
frame.add(lbl);
frame.pack();
frame.setVisible(true);
return false;
}
private void edit() {
if (Desktop.isDesktopSupported()) {
String type = assetTypes.getSelected();
String dir = getAssetDir(type);
if (type.equals("images") || type.equals("atlases"))
dir += "/1";
try {
Desktop.getDesktop().open(new File(dir));
} catch (IOException e1) {
String msg = "Something went wrong while opening assets folder.\n\n" + e1.getClass().getSimpleName()
+ " - " + e1.getMessage();
Message.showMsgDialog(getStage(), "Error", msg);
}
}
}
private static boolean editDESKTOP(File file) {
logOut("Trying to use Desktop.getDesktop().edit() with " + file);
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
logErr("EDIT is not supported.");
return false;
}
Desktop.getDesktop().edit(file);
return true;
} catch (Throwable t) {
logErr("Error using desktop edit.", t);
return false;
}
}
public void loadUri(String uri, boolean isTray, boolean isStartup) {
String url = "http://127.0.0.1:" + FRONT_PORT + (uri == null ? "" : uri);
boolean autoOpen = PDownConfigContent.getInstance().get().isAutoOpen();
if (OsUtil.isWindowsXP() || PDownConfigContent.getInstance().get().getUiMode() == 0) {
if (!isStartup || autoOpen) {
try {
Desktop.getDesktop().browse(URI.create(url));
} catch (IOException e) {
LOGGER.error("Open browse error", e);
}
}
} else {
Platform.runLater(() -> {
if (uri != null || !browser.isLoad()) {
browser.load(url);
}
if (!isStartup || autoOpen) {
show(isTray);
}
});
}
}
private static boolean browseDESKTOP(URI uri) {
logOut("Trying to use Desktop.getDesktop().browse() with " + uri.toString());
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
logErr("BROWSE is not supported.");
return false;
}
Desktop.getDesktop().browse(uri);
return true;
} catch (Throwable t) {
Log.errorDialog("Error using desktop browse.", t.getMessage() + "\nTrying: " + uri.toString());
return false;
}
}
/**
* 使用默认程序打开文件
*
* @param path
*/
private void openFileWithDefaultApplication(String path) {
try {
Desktop.getDesktop().open(new File(path));
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "文件打开失败,没有找到关联的应用程序", "打开失败", JOptionPane.ERROR_MESSAGE);
try {
java.awt.Desktop.getDesktop().open((new File(path)).getParentFile());
} catch (IOException e) {
}
e1.printStackTrace();
} catch (IllegalArgumentException e2) {
JOptionPane.showMessageDialog(null, "文件不存在,可能已被删除", "打开失败", JOptionPane.ERROR_MESSAGE);
}
}
private HtmlBrowserComponent createExternalBrowser() {
Factory browser = IDESettings.getExternalWWWBrowser();
if (browser == null) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
browser = new DesktopBrowser(desktop);
} else {
//external browser is not available, fallback to swingbrowser
browser = new SwingBrowser();
}
}
return new HtmlBrowserComponent(browser, true, true);
}
private void initSiteLink(JLabel label, MouseListener mouseListener) {
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
return;
}
label.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
label.setForeground(Color.blue);
label.addMouseListener(mouseListener);
}
/**
* Opens the documentation directory.
*/
public void openDocDir() {
File docDir = new File(DrMIPS.path + File.separator + DrMIPS.DOC_DIR);
File docDir2 = new File(DrMIPS.DOC_DIR2);
File dir;
if(docDir.isDirectory())
dir = docDir;
else if(docDir2.isDirectory())
dir = docDir2;
else {
JOptionPane.showMessageDialog(this, Lang.t("doc_dir_not_found"), AppInfo.NAME, JOptionPane.ERROR_MESSAGE);
return;
}
if(!Desktop.isDesktopSupported()) {
LOG.log(Level.WARNING, "Desktop class is not supported in this system");
JOptionPane.showMessageDialog(this, Lang.t("failed_to_open_doc_folder", dir.getAbsolutePath()), AppInfo.NAME, JOptionPane.ERROR_MESSAGE);
return;
}
if(!openDocIndex(dir)) { // try to open index.html
// if failed, try to open the directory
try {
Desktop.getDesktop().open(dir);
}
catch(Exception ex) {
LOG.log(Level.WARNING, "error opening doc folder", ex);
JOptionPane.showMessageDialog(this, Lang.t("failed_to_open_doc_folder", dir.getAbsolutePath()), AppInfo.NAME, JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* 开始更新
*/
public static void upgrade() {
//Runtime rt = Runtime.getRuntime();
//StringBuffer result = new StringBuffer();
try {
String upgradeCmd = download();
if(upgradeCmd == null) {
logger.error("更新失败");
return;
}
logger.info("更新命令: "+upgradeCmd);
Desktop.getDesktop().open(new File(upgradeCmd));
System.exit(0);
//Process p = rt.exec(upgradeCmd);
//p.waitFor();
// InputStream fis = p.getInputStream();
// InputStreamReader isr = new InputStreamReader(fis,"GBK");
// BufferedReader br = new BufferedReader(isr);
// String line = null;
// while ((line = br.readLine()) != null) {
// result.append(line);
// result.append("\r\n");
// }
// logger.info(result.toString());
}catch(Exception e) {
e.printStackTrace();
}
}
private void doOpenDocumentation() {
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(DOCUMENTATION_URL));
} catch (URISyntaxException | IOException ex) {
}
}
private void openHowToUseLink()
{
try
{
String howToLink =
"https://www.wurstclient.net/Mods/Force_OP_(AuthMeCracker)/";
Desktop.getDesktop().browse(URI.create(howToLink));
}catch(IOException e2)
{
throw new RuntimeException(e2);
}
}
/**
* Launches a file browser or opens a file with java Desktop.open() if is
* supported
*
* @param filePath
*/
private void launchFile(String filePath) {
if (filePath == null || filePath.trim().length() == 0)
return;
if (!Desktop.isDesktopSupported())
return;
Desktop dt = Desktop.getDesktop();
try {
dt.browse(getFileURI(filePath));
} catch (Exception ex) {
ex.printStackTrace();
}
}