Images in applet components

I'm developing an applet that contains a Swing GUI. The applet has a DesktopPane which contains several internal frames. These internal frames are meant to be instantiated and added on the fly depeding on user input, so all of thier setup code is contained in thier specific classes, which extend from JInternalFrame.
The Problem is that in the frames I want to use labels and buttons with icons. I am unable to load the images into the frames. I can open an image in the applet class using the getCodeBase method to get to the file name, but I know of no way to get the code base from within the components added to the applet.
Is there any way to load an image from a child componenet, or a way to get the codebase of the parent applet?

That did work very wel, but now I'm left with a new problem. The class getrus the URL for the code base, and it looks the same as the original from the applet. However, when I go to create an ImageIcon using this URL, and add it to a component I get no display. No error occurs, and the applet runs fine but the image doesn't display.

Similar Messages

  • Problem with display of images in applets

    Hi all,
    When I run this program, the appletviewer window is showing no output (i.e. no image). I'm using the netbeans IDE 5.0.
    Blue hills.jpg is present in both the src folder and build folder.
    * <applet code="image" width =800 height=600>
    * <param name="img" value="Blue hills.jpg">
    * <\applet>
    import java.awt.*;
    import java.applet.*;
    public class image extends Applet {
    Image img;
    public void init() {
    img=getImage(getDocumentBase(), getParameter("img"));
    public void paint(Graphics g){
    g.drawImage(img,0,0,this);
    Please help in figuring out the problem....

    It will be looking for it in the folder with the HTML that invokes the applet.
    If you want to pack the image in with the applet then use getResource instead.
    And spaces in the name are probably not the best idea.

  • How to move multiple images in applet

    Hi,how to move multiple images in applet or random images in applet .
    Means moving images.gif around the applet with different starting point ,help me to create that move method ..

    why don't you check the tumbling duke applet as provided free in this site? :-)

  • Display images in applets

    hi every body.
    I want to display images in an applet when i invoke it from the jsp page . it is not working. the code is as follows.
    <html>
    <body>
    <jsp:plugin type = "applet"
         code ="Welcome.class"
         width="475" height = "350" >
    </jsp:plugin>
    </body>
    </html>
    while the code of "Welcome.java" is as follows.
    ImageIcon image = new ImageIcon("aa.gif");
    JButton button = new JButton(image);
    i have placed the aa.gif file in the same directory where i placed the Welcome.class and the jsp file.
    when i run this program the i recieve the message that the applet is not loaded.
    can some body help me how to place images in applets.
    thanks.

    You should be able to test that applet on you hard drive first. If it works check the case of the image file.
    Web servers look for case. If you are asking for ImageIcon img = new ImageIcon("abc.gif") and what is loaded on your web server is "abc.GIF" it won't find it. Same goes for basic HTML tags like
    <Img src=abc.gif>. But it will find it on you hard drive when you run the applet there.

  • Help with images within applets

    I created a card game applet which calls images placed within the same directory. In appletviewer the game runs fine,not in browsers. I downloaded the browser plugin since i use swing classes. If I remove the image the applet loads up without the grafix. Here is the IO error generated. I thought applets can read files within the same directory and sub directories? Would creating a jar file solve this problem? Anyhelp would be appreciated.
    java.security.AccessControlException: access denied (java.io.FilePermission main2.gif read)

    When running in a browser, your applet must be signed in order to be able to access local resources. Check out the "Signed Applets" forum for many discussions about this, as well as methods for signing applets.

  • Accessing images from shared components

    I am having problem finding out images from shared components. After loading my images from my desktop to shared components folder, when i try to create an image item, and click the browse button, it pulls out my hard drive for selection. i don't know how to get the images already in shared components. i read in the help file that if i know the name of the image, then i can write it down and portal will pull it out. but what if i don't remember. do i have to go to shared components to find what it is and then come back and write it in the textbox?how to get to shared components clicking browse and selecting the image we want which is already stored in portal?
    thanks
    valli

    There's no way to browse and select the images in shared components. You need to know the URL to the image if you want to reference it in an item.

  • Saving image in applet

    i used the following code to save a image it displays from applet.it works fine in appletviewer
    BufferedImage expImage = new BufferedImage( (int)this.getWidth(), (int)this.getHeight(), BufferedImage.TYPE_INT_RGB );
    Graphics g2d = expImage.getGraphics();
    // draftGrid.update(g2d);
    this.update(g2d);
    g2d.dispose();
    OutputStream out = new FileOutputStream( "guru.jpg");
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(expImage);
    out.flush();
    out.close();
    expImage.flush();
    but when i run it in html through my web server the image does' get saved and it the exception i go is
    Status code:404 request:R( j
    ava/awt/image/BufferedImage.class + null) msg:null
    what should i go to save a image from applet throgh browser

    Hello,
    This is what I am doing through a servlet call.
    If you are just going to let the user download the image you could try the following:
    // This works if we are just going to download the image as is
    URL url = new URL(request.getParameter("imageURL"));
    response.setContentType("image/gif");
    response.setHeader("Content-Disposition", "attachment; "+
         "filename=\"image.gif\"");
    byte buf[] = new byte[1024];
    InputStream inputStream = url.openStream();
    ServletOutputStream out = response.getOutputStream();
    //Read and Write
    while(inputStream.read(buf) != -1)
    out.write(buf);
    out.flush();
    out.close();
    Or if you are going to manipulate the image a bit before they download it you could try the following:
    URL url = new URL(request.getParameter("imageURL"));
    response.setContentType("image/gif");
    response.setHeader("Content-Disposition", "attachment; "+
         "filename=\"image.gif\"");
    // use ImageIcon because we are getting the image from a
    // URL which might be slow - it has the MediaTracker built right in
    javax.swing.ImageIcon ii = new javax.swing.ImageIcon(url);
    Image image = ii.getImage(); // now the pixel data is in memory
    // get the height and width of the loaded image
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    // create a rectangle as big as the image
    Rectangle drawRect = new Rectangle(10, 10, width, height);
    BufferedImage bufImage = new BufferedImage(width,
    height, BufferedImage.TYPE_INT_RGB);
    // get the graphics so you can draw on it
    Graphics2D g = bufImage.createGraphics();
    // create a nicce white background for the image
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    // reset the color
    g.setColor(Color.black);
    // add the image
    g.drawImage(image, 0, 0, null);
    // add any other things you want as well
    g.drawString("Just a string", 10, 10);
    // create the output stream
    ServletOutputStream out = response.getOutputStream();
    JPEGImageEncoder jpegImageEncoder = JPEGCodec.createJPEGEncode(out);
    // encode it
    jpegImageEncoder.encode(bufImage);
    out.flush();
    out.close();
    Hope that this helps.
    Mike

  • Impossible to save an image in applet?

    I have been working on saving an image in Java applet for a week. But I failed to generate new image file on the disk. I'm using Java SDK1.4.0_03 and JAI 1_1_1_01. I found a topic "JAI TIFF Encoding Problem" mentioned that it should give permission to the Applet. I'm wondering if my problem is caused by the permission of Applet. But how to change the permissio of Applet? Otherwise is it impossible to save the image in Applet? Thanks your replay.

    Re : Thanks your replay.
    I have been working on saving an image in Java applet
    for a week. But I failed to generate new image file on
    the disk. I'm using Java SDK1.4.0_03 and JAI 1_1_1_01.
    I found a topic "JAI TIFF Encoding Problem" mentioned
    that it should give permission to the Applet. I'm
    wondering if my problem is caused by the permission of
    Applet. But how to change the permissio of Applet?
    Otherwise is it impossible to save the image in
    Applet? Thanks your replay. You're welcome :)

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
          jf.setContentPane(getJContentPane());
                     FileDialog fd=new FileDialog(jf,"hi");
                     fd.setMode(FileDialog.LOAD);
                     fd.setVisible(true);   
                     v=new Vector();
                     try{                                                
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               fis.read(imgbuffer);
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                               v.add(0,imgicon);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setDoInput(true); 
                                servletCon.setDoOutput(true);
                                servletCon.setUseCaches(false);
                                servletCon.setDefaultUseCaches(false);   
                                servletCon.setRequestMethod("POST");     
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                servletCon.connect();            
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                oboutStream.writeObject(v);
                                v.remove(0);
                                oboutStream.flush();      
                                oboutStream.close();  
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                                 imgicon=(ImageIcon)v.get(1);
                                 showimg.setIcon(imgicon);
                                 this.getContentPane().validate();
                                 this.validate();  
                                inputStream.close();                                                        
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
                          imgicon=(ImageIcon)v.get(0);                     
                          inputFromjsp.close();            
                          System.out.println(imgicon.getDescription());                                      
                          v.remove(0);
                          v.add(1,imgicon);
    //sending back to applet
                           response.setContentType("application/octet-stream");
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                          oboutstream.writeObject(v);
                          oboutstream.flush();
                          oboutstream.close();
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    thanks
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at http://www.theserverside.com/tt/articles/article.tss?l=HttpClient_FileUpload. please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the servlet.is the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    thanks
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • Absent images in shared components

    I can't see list of images in "Shared Components > Images", but wget http://10.20.50.77:7777/i/16admin.gif return current image from apex/image directory. Where I can see what is wrong?
    APEX 3.2.1
    ORACLE XE
    Standalone Oracle HTTP Server (Apache2)
    dads.conf:
    Alias /i/ "/home/apache1/data/data/apex/images/"
    httpd.conf:
    Alias /i/ "/home/apache1/data/data/apex/images/"
    <Directory "/home/apache1/data/data/apex/images/">
    Options MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
    </Directory>
    Edited by: lvccgd on 24.02.2010 1:21

    Hello,
    The images in Shared Components -> Images are ones you have uploaded specifically for your application (or workspace). They are unrelated (strictly speaking) to the images in the /i/ folder (which are either stored on the filesystem if you use the OHS or stored in the DB if you use the EPG etc).
    Hope this helps,
    John.
    Blog: http://jes.blogs.shellprompt.net
    Work: http://www.apex-evangelists.com
    Author of Pro Application Express: http://tinyurl.com/3gu7cd
    REWARDS: Please remember to mark helpful or correct posts on the forum, not just for my answers but for everyone!

  • Looking for Image Button Applet

    I'm looking for a simple image button applet (normal state, mouse-over and mouse-click) which can refer to a HTML or start a Javascript function. Can anyone help?
    Kippie

    Hi,
    This is the source code. I don't quite understand what I should do with the tokens. I hope this is allright. Thanks for your help
    Kippie.
    import java.net.URL;
    import java.awt.Color;
    import java.util.Vector;
    import java.util.Enumeration;
    import java.util.StringTokenizer;
    import java.applet.Applet;
    import java.applet.AudioClip;
    Program Name:     ImageURLButtonBar
         Author:               Paul Whitelock
         Version:          1.1
         Copyright:          (c) 1997 by Paul Whitelock and Modern Minds, Inc.
         Requires:          ImageURLButtonBar.class
                             ButtonBar.class
                             ButtonBarObserver.class (Interface definition)
                             ButtonRegion.class
                             ButtonAnimate.class
    Modifications: v1.01 (15 April 97)
                             *     Added "sticky" button behavior (controlled
                                  by applet "stick" parameter)
                             v1.03 (25 June 97)
                             *     Added applet parameter "useCodeBase". If useCodeBase
                                  is true, then image file locations will be based on the directory
                                  in which the Java class files are located. If useCodeBase is false, then
                                  the locations will be based on the HTML directory. Note that audio
                                  file locations are always based on the Java directory. The default
                                  for useCodeBase is false (use HTML directory for base).
                             *     The "stick" parameter will now accept a button number in
                                  addition to the value of "true" or "false". If a button number
                                  is specified, then that button will be "stuck" down
                                  when the button bar initializes.
                             *     Added the capability of loading multiple URLs for each button
                                  with an optional target for each URL.
                             v1.1 (25 September 97)
                             *     Added "baseBrighten" and "baseBrightenTint" parameters to control
                                  highlighting for base button bar.
                             *     Added "mouseOverBrighten" and "moBrightenTint" parameters to control
                                  highlighting for base button bar.
                             *     Added "mdBrightenTint" and "mdBrightenAll" parameters to control
                                  highlighting for base button bar. Previous versions of the applet
                                  supported "mouseDownBrighten," but only if button borders were not
                                  drawn for the button-down button bar (the "mdBrightenAll" can be set
                                  to "true" to override the this default behavior).
                             *     An "appletBGColor" parameter has been added to set the
                                  applet background color. The applet background color is
                                  sometimes visible during scrolling or during a page repaint.
         NOTE:               This source code was composed using Microsoft Visual J++
                             with tab stops of 4. Text may not be formatted correctly
                             if another editor is used.
         ******************************** PARAMETERS ********************************
              Applet Parm               ButtonBar Class Parm     Default Value
              ================== =======================     ==================
              appletBGColor
              disableBadURL                                        true
              mouseEnterAudio                                        null (audio disabled)
              mouseClickAudio                                        null (audio disabled)
              buttonDownAudio                                        null (audio disabled)
              stick                                                  false
         *     useCodeBase               base                         false (i.e., use getDocumentBase())
              orient                    barHorizontal               horizontal if applet width > height
              base                    baseBarName                    none - parameter REQUIRED
              mouseOver               mouseOverBarName          null
              mouseOver2               mouseOverBar2Name          null
              mouseDown               mouseDownBarName          null
              mouseDownOver          mouseDownOverBarName     null
              buttonsDisabled          buttonsDisabledBarName     null
              background               backgroundImageName          null
              barXPos                    barXBackgroundPos          0
              barYPos                    barYBackgroundPos          0
              buttonBorders          drawButtonBorders          ButtonBar.BORDERS_NONE
              borderColorTL          borderColorTopLeft          null (Color.white if error)
              borderColorBR          borderColorBottomRight     null (Color.gray if error)
              borderIntensity          borderIntensityPercent     50 (used only if borders)
              borderSize               buttonBorderSize          1 (used only if borders)
              downShift               downShift                    false
              downShiftAmt          downShiftAmt               buttonBorderSize
              baseBrighten          baseBrightenPct
              baseBrightenTint     baseBrightenTint
              mouseOverBrighten     mouseOverBrightenPct
              moBrightenTint          mouseOverBrightenTint
              mouseDownBrighten     mouseDownBrightenPct     
              mdBrightenTint          mouseDownBrightenTint
              mdBrightenAll          mouseDownBrightenAll
              buttonsDisabledDim     buttonsDisabledDimPct     25     (used only if no buttonsDisabled)
              grayBarBrighten          grayBarBrighten               0
              frameRate               frameRate                    150 (used only if mouseOver2)
         *     If useCodeBase is true, then all file locations are based on the Java class file
              directory (i.e., use getCodeBase()).
    public class ImageURLButtonBar extends Applet implements ButtonBarObserver {
         // Instance Variables
         ButtonBar buttonBar;
         Vector buttonURL = new Vector(10, 10);
         Vector buttonURLTarget = new Vector(10, 10);
         Vector buttonDescription = new Vector(10, 10);
         AudioClip mouseEnterAudio = null;
         AudioClip mouseClickAudio = null;
         AudioClip buttonDownAudio = null;
         // Applet Initialization
         public void init() {
              // =================================================================
              // Applet ImageURLButtonBar specific parameters
              // =================================================================
              // appletBGColor
              //          Set applet background color
              String parm = getParameter("appletBGColor");
              if (parm != null) {
                   try {     
                        setBackground(new Color(Integer.parseInt(parm, 16)));
                   catch (Exception e) {
                        reportError("appletBGColor");
              // disableBadURL
              //          If true, then any button with an invalid URL will be disabled
              parm = getParameter("disableBadURL");
              boolean disableBadURL;
              if (parm == null || !parm.equals("false")) disableBadURL = true;
              else disableBadURL = false;
              // mouseEnterAudio
              //          Sound to play each time the mouse enters any of the buttons
              parm = getParameter("mouseEnterAudio");
              if (parm != null) {
                   mouseEnterAudio = getAudioClip(getCodeBase(), parm);
                   if (mouseEnterAudio == null) reportError("Can't load " + parm);
              // mouseClickAudio
              //          Sound to play each time a mouse down click occurs in a button
              parm = getParameter("mouseClickAudio");
              if (parm != null) {
                   mouseClickAudio = getAudioClip(getCodeBase(), parm);
                   if (mouseClickAudio == null) reportError("Can't load " + parm);
              // buttonDownAudio
              //          Sound to play each time a mouse up occurs in a button (i.e, the
              //          button has be toggled through it's "down" position)
              parm = getParameter("buttonDownAudio");
              if (parm != null) {
                   buttonDownAudio = getAudioClip(getCodeBase(), parm);
                   if (buttonDownAudio == null) reportError("Can't load " + parm);
              // stickyBar
              //          If the "stick" applet parameter is "true", then buttons will stay
              //          "stuck" in the down position until another button is clicked.
              //          If the "stick" applet parameter is the number of a button in the
              //          button bar, then that button will be "stuck" down when the
              //          button bar initializes.
              int stickyBar = -1;
              parm = getParameter("stick");
              if (parm != null && !parm.toLowerCase().equals("false")) {
                   try {
                        stickyBar = Integer.parseInt(parm);
                   catch (Exception e) {
                        stickyBar = 0;
              // =================================================================
              // Class ButtonBar specific parameters
              // =================================================================
              // orient (barHorizontal)
              //          If this parameter = 'h' then the button bar is horizontal
              //          If this parameter = 'v' then the button bar is vertical
              //          If this parameter is not specified, then the button bar is
              //          horizontal if the applet width is greater than the applet height
              boolean horizontal;
              parm = getParameter("orient");
              if (parm == null) horizontal = size().width > size().height;
              else horizontal = parm.equals("h") ? true : false;
              // base     (baseBarName)
              //          The base image file for the buttons. This is the only image
              //          file that MUST be specified.
              String baseBar = getParameter("base");
              if (baseBar == null) {
                   reportError("Parameter 'base' REQUIRED!");
                   return;
              // barXPos (barXBackgroundPos)
              // barYPos (barYBackgroundPos)
              //          If a background image is specified then these to parameters
              //          represent the top-left corner location where the button bar
              //          should be placed on the background
              int barXPos = 0, barYPos = 0;
              try {
                   parm = getParameter("barXPos");
                   if (parm != null) barXPos = Integer.parseInt(parm);
                   parm = getParameter("barYPos");
                   if (parm != null) barYPos = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("barXPos or barYPos");
                   barXPos = barYPos = 0;
              // buttonBorders (drawButtonBorders)
              //          "none" = do not draw any button borders
              //          "all"     = draw borders around all button bar buttons
              //          "base"     = draw borders only around buttons on base button bar
              //          "other"     = draw borders around all button bar buttons EXCEPT base button bar buttons
              parm = getParameter("buttonBorders");
              int drawButtonBorders = ButtonBar.BORDERS_NONE;
              if (parm != null) {
                   if (parm.equals("base")) drawButtonBorders = ButtonBar.BORDERS_BASE;
                   else if (parm.equals("other")) drawButtonBorders = ButtonBar.BORDERS_OTHER;
                   else if (parm.equals("all")) drawButtonBorders = ButtonBar.BORDERS_ALL;
              // borderColorTL (borderColorTopLeft)
              // borderColorBR (borderColorBottomRight)
              //          Normally, borders are drawn around buttons by lightening or darkening
              //          the image in the border region. A specific color can be used instead
              //          for the top and left borders and/or the bottom and right borders. The
              //          value specified for either of these two parameters should be a hexadecimal
              //          number (e.g., "FF0000" for red, "888888" for medium gray, etc.).
              Color borderColorTopLeft = null;
              Color borderColorBottomRight = null;
              try {
                   parm = getParameter("borderColorTL");
                   if (parm != null) borderColorTopLeft = new Color(Integer.parseInt(parm, 16));
                   parm = getParameter("borderColorBR");
                   if (parm != null) borderColorBottomRight = new Color(Integer.parseInt(parm, 16));
              catch (Exception e) {
                   reportError("borderColorTL or borderColorBR");
                   borderColorTopLeft = Color.white;
                   borderColorBottomRight = Color.gray;
              // borderIntensity (borderIntensityPercent)
              //          If borders are drawn for buttons, and if a border color is not specified
              //          (see above), then the image in the border region will be lightened or
              //          darkened by this percentage to create the borders.
              int borderIntensityPercent = 50;
              try {
                   parm = getParameter("borderIntensity");
                   if (parm != null) borderIntensityPercent = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("borderIntensity");
                   borderIntensityPercent = 50;
              // borderSize (buttonBorderSize)
              //          The size of borders, if borders are specified.          
              int buttonBorderSize = 1;
              try {
                   parm = getParameter("borderSize");
                   if (parm != null) buttonBorderSize = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("borderSize");
              // downShift
              //          If true, then the button image is shift down and right downShiftAmt
              //          (see below) pixels when the mouse is clicked on the button.
              parm = getParameter("downShift");
              boolean downShift = (parm == null || !parm.equals("true")) ? false : true;
              // downShiftAmt
              //          If downShift is true, then the button image is shift down and right
              //          downShiftAmt (see above) pixels when the mouse is clicked on the button.
              int downShiftAmt = buttonBorderSize;
              try {
                   parm = getParameter("downShiftAmt");
                   if (parm != null) downShiftAmt = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("downShiftAmt");
              // baseBrighten (baseBrightenPct)
              //          The base bar will be lightened by this percentage
              int baseBrightenPct = 0;
              try {
                   parm = getParameter("baseBrighten");
                   if (parm != null) baseBrightenPct = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("baseBrighten");
              // mouseOverBrighten (mouseOverBrightenPct)
              //          A button will be lightened by this percentage when the mouse
              //          moves over a button.
              int mouseOverBrightenPct = 0;
              try {
                   parm = getParameter("mouseOverBrighten");
                   if (parm != null) mouseOverBrightenPct = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("mouseOverBrighten");
              // mdBrightenAll (mouseDownBrightenAll)
              //          A button will be lightened by this percentage when the mouse
              //          moves over a button.
              boolean mouseDownBrightenAll = false;
              parm = getParameter("mdBrightenAll");
              if (parm != null && parm.charAt(0) == 't') mouseDownBrightenAll = true;
              // mouseDownBrighten (mouseDownBrightenPct)
              //          A button will be lightened by this percentage when it is
              //          clicked.
              int mouseDownBrightenPct = 0;
              try {
                   parm = getParameter("mouseDownBrighten");
                   if (parm != null) mouseDownBrightenPct = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("mouseDownBrighten");
              // baseBrightenTint (mouseOverBrightenTint)
              // moBrightenTint (mouseOverBrightenTint)
              // mdBrightenTint (mouseDownBrightenTint)
              Color baseBrightenTint = null;
              Color mouseOverBrightenTint = null;
              Color mouseDownBrightenTint = null;
              try {
                   parm = getParameter("baseBrightenTint");
                   if (parm != null) baseBrightenTint = new Color(Integer.parseInt(parm, 16));
                   parm = getParameter("moBrightenTint");
                   if (parm != null) mouseOverBrightenTint = new Color(Integer.parseInt(parm, 16));
                   parm = getParameter("mdBrightenTint");
                   if (parm != null) mouseDownBrightenTint = new Color(Integer.parseInt(parm, 16));
              catch (Exception e) {
                   reportError("baseBrightenTint, moBrightenTint or mdBrightenTint");
              // buttonsDisabledDim (buttonsDisabledDimPct)
              //          If a button is disabled and if there is no buttonsDisabled image,
              //          then the button will be dimmed by this percentage.
              int buttonsDisabledDimPct = 25;
              try {
                   parm = getParameter("buttonsDisabledDim");
                   if (parm != null) buttonsDisabledDimPct = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("buttonsDisabledDim");
              // grayBarBrighten
              //          If there is no mouseOver image, then the base image will be used for
              //          the mouseOver image, and a grayscale version of the base image will
              //          be used for base button images. This parameter can be used to lighten
              //          COLORS (not grays) in the image before it is converted to grayscale.
              //          This can help if the standard conversion produces buttons that are
              //          too dark.
              int grayBarBrighten = 0;
              try {
                   parm = getParameter("grayBarBrighten");
                   if (parm != null) grayBarBrighten = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("grayBarBrighten");
              // frameRate
              //          If a mouseOver2 image is specified, then this parameter controls
              //          how quickly animation will be performed (using mouseOver and mouseOver2
              //          images) in milliseconds when the mouse is moved over a button.
              int frameRate = 150;
              try {
                   parm = getParameter("frameRate");
                   if (parm != null) frameRate = Integer.parseInt(parm);
              catch (Exception e) {
                   reportError("frameRate");
              // =================================================================
              // Instantiate the button bar
              // =================================================================
              try {
                   // Allow the use of documentBase (default) or codeBase for image file
                   // base directory.
                   URL documentBase;
                   parm = getParameter("useCodeBase");
                   if (parm == null || parm.equals("false")) documentBase = getDocumentBase();
                   else documentBase = getCodeBase();
                   // Create the button bar
                   buttonBar = new ButtonBar(
                                                 horizontal,                         /* barHorizontal */
                                                 documentBase,                         /* base */
                                                 baseBar,                              /* baseBarName */
                                                 getParameter("mouseOver"),     /* mouseOverBarName */
                                                 getParameter("mouseOver2"),     /* mouseOverBar2Name */
                                                 getParameter("mouseDown"),     /* mouseDownBarName */
                                                 getParameter("mouseDownOver"), /* mouseDownOverBarName */
                                                 getParameter("buttonsDisabled"),/* buttonsDisabledBarName */
                                                 getParameter("background"),     /* backgroundImageName */
                                                 barXPos,                              /* barXBackgroundPos */
                                                 barYPos,                              /* barYBackgroundPos */
                                                 drawButtonBorders,               /* drawButtonBorders */
                                                 borderColorTopLeft,               /* borderColorTopLeft */
                                                 borderColorBottomRight,          /* borderColorBottomRight */
                                                 borderIntensityPercent,          /* borderIntensityPercent */
                                                 buttonBorderSize,                    /* buttonBorderSize */
                                                 downShift,                         /* downShift */
                                                 downShiftAmt,                         /* downShiftAmt */
                                                 baseBrightenPct,                    /* baseBrightenPct */
                                                 baseBrightenTint,                    /* baseBrightenTint */
                                                 mouseOverBrightenPct,               /* mouseOverBrightenPct */
                                                 mouseOverBrightenTint,          /* mouseOverBrightenTint */
                                                 mouseDownBrightenAll,               /* mouseDownBrightenAll */
                                                 mouseDownBrightenPct,               /* mouseDownBrightenPct */
                                                 mouseDownBrightenTint,          /* mouseDownBrightenTint */
                                                 buttonsDisabledDimPct,          /* buttonsDisabledDimPct */
                                                 grayBarBrighten,                    /* grayBarBrighten */
                                                 frameRate                              /* frameRate */     
                   // =================================================================
                   // Add buttons to the button bar
                   // =================================================================
                   ButtonRegion buttonToAdd;
                   String buttonNbr, urlString;
                   URL urlForButton;
                   int nbr = 0;
                   int buttonStart, buttonSize;
                   // Initialize button on bar flag (used to determine if at least one button
                   // was successfully added to the button bar)
                   boolean buttonOnBar = false;
                   // This loop will be exited when no more buttons can be found in the HTML
                   while (true) {
                        // Construct the prefix for the button parameters
                        buttonNbr = "button" + ++nbr;
                        // Find the starting offset and the size of the button
                        // If null is returned as the starting offset parameter value for the
                        // button, then all buttons should have been read so the loop can
                        // be exited.
                        try {
                             parm = getParameter(buttonNbr + "Start");
                             if (parm == null) break;
                             buttonStart = Integer.parseInt(parm);
                             buttonSize = Integer.parseInt(getParameter(buttonNbr + "Size"));
                        catch (Exception e) {
                             reportError("Button" + nbr + " start or size in error or missing");
                             buttonStart = 0;
                             buttonSize = 0;
                        // Create a ButtonRegion for the button
                        // The button ID will be set to the number of the button (this will
                        // be converted to an integer later when a buttonBarEvent is received).
                        buttonToAdd = new ButtonRegion("" + nbr, buttonStart, buttonSize);
                        // If the buttons on this button bar are "sticky" buttons, then
                        // enable "sticky" behavior for this button. The button will always
                        // "pop-up" whenever another button is clicked.
                        if (stickyBar >= 0) {
                             buttonToAdd.stickyButton(true, ButtonRegion.POPUP_ALWAYS, false);
                             // If the current button number matches the value of stickyBar, then the
                             // current button should be "stuck" down for its initial state.
                             if (stickyBar == nbr) buttonToAdd.setStuck(true);
                        // Try to add the button (i.e., the ButtonRegion) to the buttonBar
                        if (buttonBar.addButton(buttonToAdd)) {
                             // Set flag to indicate that at least one button has been added
                             buttonOnBar = true;
                             // The button was successfully added, so save the button's description
                             // (which will be displayed in the status bar) and the target frame
                             // for the button URL in the appropriate Vector.
                             buttonDescription.addElement(getParameter(buttonNbr + "Desc"));
                             buttonURLTarget.addElement(getParameter(buttonNbr + "Target"));
                             // Try to create a URL for the button.
                             // If the URL is invalid, then place an error message in the
                             // buttonURLTarget Vector (this will be used to warn the user
                             // when the button is clicked). Also, if disableBadURL is true, then
                             // disable the button.
                             String theURL;
                             urlString = getParameter(buttonNbr + "URL");
                             if (urlString != null) {
                                  Enumeration urls = new StringTokenizer(urlString);
                                  while (urls.hasMoreElements()) {
                                       theURL = (String)urls.nextElement();
                                       try {
                                            urlForButton = new URL(theURL);
                                       catch (Exception e) {
                                            try {
                                                 urlForButton = new URL(getDocumentBase(), theURL);
                                            catch (Exception e2) {
                                                 reportError("Button" + nbr + " has invalid URL");
                                                 buttonURLTarget.setElementAt("Invalid URL", nbr - 1);
                                                 urlString = null;
                                                 break;
                             else {
                                  reportError("Button" + nbr + " has no URL");
                                  buttonURLTarget.setElementAt("No URL", nbr - 1);
                             buttonURL.addElement(urlString);
                   // Remove any unused elements in the Vectors
                   buttonURL.trimToSize();
                   buttonURLTarget.trimToSize();
                   buttonDescription.trimToSize();
                   // If no buttons were added, throw exception
                   if (!buttonOnBar) throw new IllegalArgumentException("No buttons on bar");
                   // Let the buttonBar know that all buttons have been defined. This is
                   // really only necessary if downShift is true, but it won't hurt calling
                   // the method in either case.
                   buttonBar.allButtonsDefined();
                   // Add the applet as an observer so that the applet will be notified
                   // when button events occur.
                   buttonBar.addButtonObserver(this);
                   // Enable the button bar now that all buttons have been defined.
                   // (the buttonBar is disabled when it is created and must be
                   // specifically enabled).
                   buttonBar.enable(true);
                   // Add the buttonBar to the applet
                   setLayout(null);
                   add(buttonBar);
              catch (Exception e) {
                   reportError("Can't create ButtonBar\n" + e);
         // buttonBarEvent
         //          This method is called by the ButtonBar whenever a button event occurs
         //          It provides the ButtonBar that the event occurred for, the button ID
         //          that the event occurred for, and the event type.
         public void buttonBarEvent(ButtonBar barID, String buttonID, int buttonEvent) {
              String description;
              // The buttonBar will send an IMAGES_READY event when all button bar images
              // have been prepared. We are not interested in this event, but only in
              // certain "action" events that occur for a button.
              if (buttonEvent != ButtonBar.IMAGES_READY) {
                   // A number in String format was assigned as the buttonID when each
                   // ButtonRegion was created. The buttonID String will now be converted
                   // back into a number that can be used as a Vector index to retrieve
                   // button specific information (i.e., URL, target frame, and description).
                   int buttonNbr = Integer.parseInt(buttonID) - 1;
                   switch (buttonEvent) {
                        // If a mouseDown event has occurred for the button, and if an
                        // AudioClip is available for this event, play the AudioClip.
                        case ButtonBar.MOUSE_CLICK:     
                             if (mouseClickAudio != null) mouseClickAudio.play();
                             break;
                        // If the mouse has been moved over a button, display the button's
                        // description in the browser's status area. If the button that the mouse
                        // is over is an active button, and if there is an AudioClip available
                        // for this event, then play the audio clip.
                        case ButtonBar.MOUSE_ENTER:     
                        case ButtonBar.MOUSE_ENTER_DISABLED:
                             description = (String)buttonDescription.elementAt(buttonNbr);
                             if (description != null) showStatus(description);
                             if (mouseEnterAudio != null && buttonEvent == ButtonBar.MOUSE_ENTER) {
                                  mouseEnterAudio.play();
                             break;
                        // If the mouse has been moved off of a button and if the button has
                        // description text associated with it, then clear the browser's
                        // browser's status area.
                        case ButtonBar.MOUSE_EXIT:
                        case ButtonBar.MOUSE_EXIT_DISABLED:
                             description = (String)buttonDescription.elementAt(buttonNbr);
                             if (description != null) showStatus("");
                             break;
                        // If the button has been depressed (i.e., a mouseDown followed by
                        // a mouseUp for the same button) then load the URL(s) for the button
                        // in the target frame(s), if specified. If the URL is null, then the
                        // URL was found to be missing or invalid, so display the text stored in
                        // the buttonURLTarget Vector in the brower's status area. If there is
                        // an AudioClip for the event, play the audio.
                        case ButtonBar.BUTTON_DOWN:
                             // Get the string of URLs and Targets for the button
                             String urlString = (String)buttonURL.elementAt(buttonNbr);
                             String targetString = (String)buttonURLTarget.elementAt(buttonNbr);
                             // If there is at least one URL for the button
                             if (urlString != null) {
                                  URL urlForButton;
                                  String theURL;
                                  String theTarget;
                                  Enumeration urls = new StringTokenizer(urlString);
                                  Enumeration targets = null;
                                  if (targetString != null) targets = new StringTokenizer(targetString);
                                  // While there is another URL for the button
                                  while (urls.hasMoreElements()) {
                                       // Get the next String token that represents a URL
                                       theURL = (String)urls.nextElement();
                                       // Convert the String to a URL
                                       try {
                                            urlForButton = new URL(theURL);
                                       catch (Exception e) {
                                            try {
                                                 urlForButton = new URL(getDocumentBase(), theURL);
                                            catch (Exception e2) {
                                                 urlForButton = null;
                                                 break;
                                       // If the String was successfully convert to a URL
                                       if (urlForButton != null) {
                                            // If there is a target for this URL
                                            if (targets != null && targets.hasMoreElements()) {
                                                 // Get the String that represents the target
                                                 theTarget = (String)targets.nextElement();
                                                 // If the target String does NOT begin with a "-",
                                                 // then load the URL in the target
                                                 if (theTarget.charAt(0) != '-') {
                                                      getAppletContext().showDocument(urlForButton, theTarget);
                                                 // Else a target for this URL should not be used
                                                 else {
                                                      getAppletContext().showDocument(urlForButton);
                                            // Else there is no target for this URL, so just show
                                            // the URL.
                                            else {
                                                 getAppletContext().showDocument(urlForButton);
                             // Else URL is missing or invalid
                             else showStatus((String)buttonURLTarget.elementAt(buttonNbr));
                             if (buttonDownAudio != null) buttonDownAudio.play();
                             break;
         // Error reporting
         private void reportError(String message) {
              message = "[ImageURLButtonBar] Error - " + message;
              System.out.println(message);
              showStatus(message);
    }

  • Loading Images into Applets

    I've been having problems loading an image into an Applet. I've found that when the getImage() call is put into the init() method it loads the image fine, also implementing an imageUpdate call. However, now I'm trying to expand on this by putting it into a button click, it hangs indefinitely while waiting for the image to load.
    Another interesting point I've noticed is that the Canvas subclass ImageSegmentSelector uses a PixelGrabber in its constructor to put the Image into a buffer - when this class is created from the imageUpdate() call, NOT the init() call, the grabPixels() call hangs indefinitely too!!
    Any feedback, please,
    Jonathan Pendrous
    import java.applet.*;
    import java.net.*;
    import jmpendrous.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class XplaneGlobalSceneryDownloader extends Applet implements ActionListener{
    ImageSegmentSelector worldMap;
    Image img;
    URL url;
    int longtitude = 36;
    int latitude = 18;
    boolean imageLoaded;
    TextField t1, t2,t3;
    Label l1,l2,l3;
    Button b1;
    Applet a1;
    public void init() {
    a1 = this;
    l1 = (Label) add(new Label("Number of horizontal sections: "));
    t1 = (TextField) add(new TextField("45",3));
    l2 = (Label) add(new Label("Number of vertical sections: "));
    t2 = (TextField) add(new TextField("45",3));
    l3 = (Label) add(new Label("URL of image file: "));
    t3 = (TextField) add(new TextField("file:///C:/java/work/xplane_project/source/world-landuse.GIF",60));
    b1 = (Button) add(new Button("Load image"));
    b1.addActionListener(this);
    validate();
    // THIS CODE WORKS FINE ...
    /*try { url = new URL("file:///C:/java/work/xplane_project/source/world-landuse.GIF"); }
    catch(MalformedURLException e) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false) { try { Thread.sleep(1000);   } catch(InterruptedException e) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();*/
    //repaint();
    //worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    //repaint();
    public void actionPerformed(ActionEvent e) {
    try { longtitude = Integer.parseInt(t1.getText()); } catch (NumberFormatException ex) {System.exit(0); }
    try { latitude = Integer.parseInt(t2.getText()); } catch (NumberFormatException e2) {System.exit(0); }
    try { url = new URL(t3.getText()); }
    catch(MalformedURLException e3) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false)
    { try { Thread.sleep(1000);   } //KEEPS ON LOOPING
    catch(InterruptedException e4) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(a1, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();
    public boolean imageUpdate(Image i, int flags, int x, int y, int w, int h){
    // THIS NEVER GETS CALLED AT ALL //
    if (((flags & ImageObserver.WIDTH) != 0) && ((flags & ImageObserver.HEIGHT) != 0)) {
    //worldMap = new ImageSegmentSelector(this, i, longtitude, latitude);
    //add(worldMap);
    //validate();
    //repaint();
    imageLoaded = true;
    return false;
    return true;
    }

    Sorry, thought this had been lost.
    You can load a file if the applet itself is run from the local filesystem - it loads it fine from the init(), but not otherwise. But I haven't got the applet to run from a browser yet without crashing (it's OK in the IDE debugger), so that's the next step.

  • Mouse clicks inside image in applet

    How can I respond to mouse clicks inside particular regions in an image loaded as part of an applet in a browser? ie, I want to send these clicks onto the server for the server to handle it and the server should change the image according to the mouse clicks.
    Thanks,

    /*  <applet code="ImageMouse" width="400" height="400"></applet>
    *  use: >appletviewer ImageMouse.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageMouse extends JApplet
        JLabel label;
        public void init()
            ImageMousePanel panel = new ImageMousePanel();
            ImageMouser mouser = new ImageMouser(panel, this);
            panel.addMouseMotionListener(mouser);
            getContentPane().add(panel);
            getContentPane().add(getLabel(), "South");
        private JLabel getLabel()
            label = new JLabel(" ");
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setBorder(BorderFactory.createTitledBorder("image coordinates"));
            Dimension d = label.getPreferredSize();
            d.height = 35;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            JApplet applet = new ImageMouse();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class ImageMousePanel extends JPanel
        BufferedImage image;
        Rectangle r;
        public ImageMousePanel()
            loadImage();
            r = new Rectangle(getPreferredSize());
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();
            r.x = (w - imageWidth)/2;
            r.y = (h - imageHeight)/2;
            g2.drawImage(image, r.x, r.y, this);
            //g2.setPaint(Color.red);
            //g2.draw(r);
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(), image.getHeight());
        private void loadImage()
            String s = "images/greathornedowl.jpg";
            try
                URL url = getClass().getResource(s);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
    class ImageMouser extends MouseMotionAdapter
        ImageMousePanel panel;
        ImageMouse applet;
        boolean outsideImage;
        public ImageMouser(ImageMousePanel imp, ImageMouse applet)
            panel = imp;
            this.applet = applet;
            outsideImage = true;
        public void mouseMoved(MouseEvent e)
            Point p = e.getPoint();
            if(panel.r.contains(p))
                int x = p.x - panel.r.x;
                int y = p.y - panel.r.y;
                applet.label.setText("x = " + x + "  y = " + y);
                if(outsideImage)
                    outsideImage = false;
            else if(!outsideImage)
                outsideImage = true;
                applet.label.setText("outside image");
    }

  • Display image in applet - need help

    Ive got this code in my applet
    Image image1 = toolkit.getImage("images/background.jpg");
    Which runs fine when run locally, but when I try to run it from a html in a browser it starts to fire off lots of security messages.
    How can i do this?
    the remainder is I set it as my background
    g.drawImage(image, 0, 0, this);

    I have tried the following while running the applet in a browser and it worked...so I guess you can give this a try...
    java.net.URL backgroundImage = getClass().getResource("back.jpg");
    ImageIcon icon = new ImageIcon(backgroundImage);
    and then use this ImageIcon to set the background.

  • Images in applet URGENT!!

    Hi. how do i display an image on an applet or a frame without using swing? Any code sample will help. Thanx
    -Raam

    try adding an icon to a Label

Maybe you are looking for

  • How do I stop icloud contacts from overwriting or superseding iphone contact entrees

    If i enter a new contact on my Iphone it eventualy gets wiped out (Deleted).  i assume this is because it does not exist on the cloud.  If i enter a new contact in the cloud, it emediatly apears on my Iphone.  Nice!  i like that, but i want to be abl

  • TOC in a stand-alone doc (ala Word)?

    Hello - I'm creating the template for our stand-alone changes document in Frame 9 (we're abandoning Word - yea!). I've looked through the User Guide and experimented, but am unable to generate a TOC on the first page of the changes doc that can be re

  • File to Mail without Mapping

    Hi Experts, I need to pick up text files from a folder using File Adapter and then send them to a mail id directly without any mapping in XI. Please suggest how it can be done. Thanks, Shobhit

  • Nokia 6230i v03.40 Language Problem

    this is very strange.... when i go into the phone settings and then languages from there only the work automatic shows there and i cant change the language of the phone the strange thing is that if i insert another SIM card into the phone it works fi

  • PSE 9 Dos not recognize NEF of D7000

    I purchased a Nikon D7000 and read that PSE 8 would not recognize the NEF files for the D7000. So I purchased PSE 9 When bridge opens it shows the NEF thumb nails for the D7000 BUT when I load the NEF pictures the pictures are white and a drop down m