Loading Image in Java Applet

后端 未结 4 585
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 21:18

When I try to run an applet in applet viewer it is not able to find resources (Image). I try to load resource like this:

String cb= this.getCodeBase().toString()         


        
4条回答
  •  难免孤独
    2021-01-21 21:58

    Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.

    private URL getURL(String filename) {
        URL url = null;
        try 
        {
            url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/ 
        }
        //catch (MalformedURLException e) { e.printStackTrace(); }
        catch (Exception e) { }
    
        return url;
    }
    

    //observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin

    public void load(String filename) {
    
        Toolkit tk = Toolkit.getDefaultToolkit();
        image = tk.getImage(getURL(filename));
        while(getImage().getWidth(observerwin) <= 0){loaded = false;}
        double x = observerwin.getSize().width/2  - width()/2;
        double y = observerwin.getSize().height/2 - height()/2;
        at = AffineTransform.getTranslateInstance(x, y);
        loaded = true;
    }
    

    I can post the rest of the class I use if needed

提交回复
热议问题