Avatar billede hono Nybegynder
30. marts 2005 - 17:38 Der er 9 kommentarer og
1 løsning

Link i java-applikation

Hvordan kan man lave et link til en hjemmeside i et javaprogram? Jeg vil altså gerne have, at når brugeren trykker på en knap så åbnes hans webbrowser og viser ham en bestemt hjemmeside.

På forhånd tak

Hono
Avatar billede simonvalter Praktikant
30. marts 2005 - 18:03 #1
under windows

Runtime.getRuntime().exec("cmd /c start www.google.dk");

linket kan du klare med en label eller lign som du lytter på.
Avatar billede simonvalter Praktikant
30. marts 2005 - 18:26 #2
du kunne også bruge jdic som kan en hel masse smart bland andet launche default browser. eksempel på koden


import java.net.URL;
import java.net.MalformedURLException;
import org.jdesktop.jdic.desktop.Desktop;
import org.jdesktop.jdic.desktop.DesktopException;

public class TestBrowse {
    public static void main(String[] args) {
        try {
            Desktop.browse(new URL("http://sceri.prc.sun.com"));
        } catch(MalformedURLException e) {
            e.printStackTrace();
        } catch (DesktopException e) {
            e.printStackTrace();
        }
    }
}

fordelen er at så skal du ikke sidde og få det til at virke under forskellige os. det skulle virke med både windows/linux og macosx

https://jdic.dev.java.net/
Avatar billede trp79 Nybegynder
31. marts 2005 - 09:04 #3
Du får også lige et alternativ. Må indrømme at simonvalter foreslag nok mindst er lige godt!

--> Simon hvilken java version kræver dit forslag? spørger fordi jeg aldrig har set det før....


Understående klasse kan bruges med:
try{
    BrowserLauncher.openURL("http://www.exp.dk");
  }
catch(Exception e){System.out.println(e);}

og skulle tilnærmelsesvis
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BrowserLauncher {
    private static int jvm;
    private static Object browser;
    private static boolean loadedWithoutErrors;
    private static Class mrjFileUtilsClass;
    private static Class mrjOSTypeClass;
    private static Class macOSErrorClass;
    /** The com.apple.MacOS.AEDesc class */
    private static Class aeDescClass;
    /** The <init>(int) method of com.apple.MacOS.AETarget */
    private static Constructor aeTargetConstructor;
    /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
    private static Constructor appleEventConstructor;
    /** The <init>(String) method of com.apple.MacOS.AEDesc */
    private static Constructor aeDescConstructor;
    /** The findFolder method of com.apple.mrj.MRJFileUtils */
    private static Method findFolder;
    /** The getFileType method of com.apple.mrj.MRJOSType */
    private static Method getFileType;
    /** The makeOSType method of com.apple.MacOS.OSUtils */
    private static Method makeOSType;
    /** The putParameter method of com.apple.MacOS.AppleEvent */
    private static Method putParameter;
    /** The sendNoReply method of com.apple.MacOS.AppleEvent */
    private static Method sendNoReply;
    /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
    private static Object kSystemFolderType;
    /** The keyDirectObject AppleEvent parameter type */
    private static Integer keyDirectObject;
    /** The kAutoGenerateReturnID AppleEvent code */
    private static Integer kAutoGenerateReturnID;
    /** The kAnyTransactionID AppleEvent code */
    private static Integer kAnyTransactionID;
    /** JVM constant for MRJ 2.0 */
    private static final int MRJ_2_0 = 0;
    /** JVM constant for MRJ 2.1 or later */
    private static final int MRJ_2_1 = 1;
    /** JVM constant for any Windows NT JVM */
    private static final int WINDOWS_NT = 2;
    /** JVM constant for any Windows 9x JVM */
    private static final int WINDOWS_9x = 3;
    /** JVM constant for any other platform */
    private static final int OTHER = -1;
    /**
    * The file type of the Finder on a Macintosh.  Hardcoding "Finder" would keep non-U.S. English
    * systems from working properly.
    */
    private static final String FINDER_TYPE = "FNDR";
    /**
    * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
    * application.
    */
    private static final String FINDER_CREATOR = "MACS";
    /** The name for the AppleEvent type corresponding to a GetURL event. */
    private static final String GURL_EVENT = "GURL";
    /**
    * The first parameter that needs to be passed into Runtime.exec() to open the default web
    * browser on Windows.
    */
    private static final String FIRST_WINDOWS_PARAMETER = "/c";
    /** The second parameter for Runtime.exec() on Windows. */
    private static final String SECOND_WINDOWS_PARAMETER = "start";
    /**
    * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
    * on many command-line systems.
    */
    private static final String NETSCAPE_OPEN_PARAMETER_START = " -remote 'openURL(";
    private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
    /**
    * The message from any exception thrown throughout the initialization process.
    */
    private static String errorMessage;
    /**
    * An initialization block that determines the operating system and loads the necessary
    * runtime data.
    */
    static {
        loadedWithoutErrors = true;
        String osName = System.getProperty("os.name");
        if ("Mac OS".equals(osName)) {
            String mrjVersion = System.getProperty("mrj.version");
            String majorMRJVersion = mrjVersion.substring(0, 3);
            try {
                double version = Double.valueOf(majorMRJVersion).doubleValue();
                if (version == 2) {
                    jvm = MRJ_2_0;
                } else if (version >= 2.1) {
                    // For the time being, assume that all post-2.0 versions of MRJ work the same
                    jvm = MRJ_2_1;
                } else {
                    loadedWithoutErrors = false;
                    errorMessage = "Unsupported MRJ version: " + version;
                }
            } catch (NumberFormatException nfe) {
                loadedWithoutErrors = false;
                errorMessage = "Invalid MRJ version: " + mrjVersion;
            }
        } else if (osName.startsWith("Windows")) {
            if (osName.indexOf("9") != -1) {
                jvm = WINDOWS_9x;
            } else {
                jvm = WINDOWS_NT;
            }
        } else {
            jvm = OTHER;
        }

        if (loadedWithoutErrors) {    // if we haven't hit any errors yet
            loadedWithoutErrors = loadClasses();
        }
    }

    /**
    * This class should never be instantiated; this just ensures so.
    */
    private BrowserLauncher() { }

    /**
    * Called by a static initializer to load any classes, fields, and methods required at runtime
    * to locate the user's web browser.
    * @return <code>true</code> if all intialization succeeded
    *            <code>false</code> if any portion of the initialization failed
    */
    private static boolean loadClasses() {
        switch (jvm) {
            case MRJ_2_0:
                try {
                    Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
                    macOSErrorClass = Class.forName("com.apple.MacOS.MacOSError");
                    Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
                    Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
                    Class aeClass = Class.forName("com.apple.MacOS.ae");
                    aeDescClass = Class.forName("com.apple.MacOS.AEDesc");

                    aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
                    appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
                    aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });

                    makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
                    putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
                    sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });

                    Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
                    keyDirectObject = (Integer) keyDirectObjectField.get(null);
                    Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
                    kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
                    Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
                    kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
                } catch (ClassNotFoundException cnfe) {
                    errorMessage = cnfe.getMessage();
                    return false;
                } catch (NoSuchMethodException nsme) {
                    errorMessage = nsme.getMessage();
                    return false;
                } catch (NoSuchFieldException nsfe) {
                    errorMessage = nsfe.getMessage();
                    return false;
                } catch (IllegalAccessException iae) {
                    errorMessage = iae.getMessage();
                    return false;
                }
                break;
            case MRJ_2_1:
                try {
                    mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
                    mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
                    Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
                    kSystemFolderType = systemFolderField.get(null);
                    findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
                    getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
                } catch (ClassNotFoundException cnfe) {
                    errorMessage = cnfe.getMessage();
                    return false;
                } catch (NoSuchFieldException nsfe) {
                    errorMessage = nsfe.getMessage();
                    return false;
                } catch (NoSuchMethodException nsme) {
                    errorMessage = nsme.getMessage();
                    return false;
                } catch (SecurityException se) {
                    errorMessage = se.getMessage();
                    return false;
                } catch (IllegalAccessException iae) {
                    errorMessage = iae.getMessage();
                    return false;
                }
                break;
        }
        return true;
    }

    /**
    * Attempts to locate the default web browser on the local system.  Caches results so it
    * only locates the browser once for each use of this class per JVM instance.
    * @return The browser for the system.  Note that this may not be what you would consider
    *            to be a standard web browser; instead, it's the application that gets called to
    *            open the default web browser.  In some cases, this will be a non-String object
    *            that provides the means of calling the default browser.
    */
    private static Object locateBrowser() {
        if (browser != null) {
            return browser;
        }
        switch (jvm) {
            case MRJ_2_0:
                try {
                    Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
                    Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
                    Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
                    Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
                    // Don't set browser = appleEvent because then the next time we call
                    // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
                    // added the relevant parameter. Instead, regenerate the AppleEvent every time.
                    // There's probably a way to do this better; if any has any ideas, please let
                    // me know.
                    return appleEvent;
                } catch (IllegalAccessException iae) {
                    browser = null;
                    errorMessage = iae.getMessage();
                    return browser;
                } catch (InstantiationException ie) {
                    browser = null;
                    errorMessage = ie.getMessage();
                    return browser;
                } catch (InvocationTargetException ite) {
                    browser = null;
                    errorMessage = ite.getMessage();
                    return browser;
                }
            case MRJ_2_1:
                File systemFolder;
                try {
                    systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
                } catch (IllegalArgumentException iare) {
                    browser = null;
                    errorMessage = iare.getMessage();
                    return browser;
                } catch (IllegalAccessException iae) {
                    browser = null;
                    errorMessage = iae.getMessage();
                    return browser;
                } catch (InvocationTargetException ite) {
                    browser = null;
                    errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
                    return browser;
                }
                String[] systemFolderFiles = systemFolder.list();
                // Avoid a FilenameFilter because that can't be stopped mid-list
                for(int i = 0; i < systemFolderFiles.length; i++) {
                    try {
                        File file = new File(systemFolder, systemFolderFiles[i]);
                        if (!file.isFile()) {
                            continue;
                        }
                        Object fileType = getFileType.invoke(null, new Object[] { file });
                        if (FINDER_TYPE.equals(fileType.toString())) {
                            browser = file.toString();    // Actually the Finder, but that's OK
                            return browser;
                        }
                    } catch (IllegalArgumentException iare) {
                        browser = browser;
                        errorMessage = iare.getMessage();
                        return null;
                    } catch (IllegalAccessException iae) {
                        browser = null;
                        errorMessage = iae.getMessage();
                        return browser;
                    } catch (InvocationTargetException ite) {
                        browser = null;
                        errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
                        return browser;
                    }
                }
                browser = null;
                break;
            case WINDOWS_NT:
                browser = "cmd.exe";
                break;
            case WINDOWS_9x:
                browser = "command.com";
                break;
            case OTHER:
            default:
                browser = "netscape";
                break;
        }
        return browser;
    }

    /**
    * Attempts to open the default web browser to the given URL.
    * @param url The URL to open
    * @throws IOException If the web browser could not be located or does not run
    */
    public static void openURL(String url) throws IOException {
        if (!loadedWithoutErrors) {
            throw new IOException("Exception in finding browser: " + errorMessage);
        }
        Object browser = locateBrowser();
        if (browser == null) {
            throw new IOException("Unable to locate browser: " + errorMessage);
        }
        switch (jvm) {
            case MRJ_2_0:
                Object aeDesc = null;
                try {
                    aeDesc = aeDescConstructor.newInstance(new Object[] { url });
                    putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
                    sendNoReply.invoke(browser, new Object[] { });
                } catch (InvocationTargetException ite) {
                    throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
                } catch (IllegalAccessException iae) {
                    throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
                } catch (InstantiationException ie) {
                    throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
                } finally {
                    aeDesc = null;    // Encourage it to get disposed if it was created
                    browser = null;    // Ditto
                }
                break;
            case MRJ_2_1:
                Runtime.getRuntime().exec(new String[] { (String) browser, url } );
                break;
            case WINDOWS_NT:
            case WINDOWS_9x:
                Runtime.getRuntime().exec(new String[] { (String) browser, FIRST_WINDOWS_PARAMETER,
                                                                    SECOND_WINDOWS_PARAMETER, url });
                break;
            case OTHER:
                // Assume that we're on Unix and that Netscape is installed

                // First, attempt to open the URL in a currently running session of Netscape
                Process process = Runtime.getRuntime().exec((String) browser +
                                                            NETSCAPE_OPEN_PARAMETER_START +    url +
                                                            NETSCAPE_OPEN_PARAMETER_END);
                try {
                    int exitCode = process.waitFor();
                    if (exitCode != 0) {    // if Netscape was not open
                        Runtime.getRuntime().exec(new String[] { (String) browser, url });
                    }
                } catch (InterruptedException ie) {
                    throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
                }
                break;
            default:
                // This should never occur, but if it does, we'll try the simplest thing possible
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
                break;
        }
    }
}
Avatar billede simonvalter Praktikant
31. marts 2005 - 10:48 #4
trp79 det burde virke med alle men det er længe siden jeg har testet det. jdic er JDesktop Integration Components som er et projekt der samler smarte funktioner som at launche en browser/email client/komme program i tray osv... altså nogen native funktioner men det skulle virke på en del platforme allerede.
Avatar billede trp79 Nybegynder
31. marts 2005 - 10:55 #5
Det lyder super simon :)
Så er der jo ikke meget grund til at benytte browserlauncher klassen mere :)
Avatar billede trp79 Nybegynder
31. marts 2005 - 11:04 #6
For at vise, at din jlable fx et et link så kan du også ændre din cursor til en "handcursor" når den er inden over din jlable. Her er et eksempel med med JTextField:
        tFWeb.setEditable(false);
        tFWeb.setForeground(new java.awt.Color(0, 0, 255));
        tFWeb.setFont(new java.awt.Font("Dialog", 0, 10));
        getContentPane().add(tFWeb);
        tFWeb.setBounds(250, 230, 170, 20);
        tFWeb.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Avatar billede hono Nybegynder
09. april 2005 - 22:42 #7
Takker for hjælpen. Simonvalter kom med et svar, så er pointene dine.

Hono
Avatar billede simonvalter Praktikant
10. april 2005 - 01:51 #8
ok :=)
Avatar billede simonvalter Praktikant
18. april 2005 - 21:23 #9
lukketid :)
Avatar billede trp79 Nybegynder
02. maj 2005 - 16:03 #10
hono?
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester