Java.awt.createFont(...) in Applet

I'm trying to dynamically load a truetype-font in an applet with Font.createFont(...) .
Unfortunately I'm always getting
java.lang.SecurityException: Unable to create temporary fileAnd, surprise, surprise, Font.createFont() requires a temporary file wich I found not to be documented in javadoc but in the source of Font.java (see last line of the next code example):
public static Font createFont ( int fontFormat, InputStream fontStream )
      throws java.awt.FontFormatException, java.io.IOException {
      if ( fontFormat != Font.TRUETYPE_FONT ) {
          throw new IllegalArgumentException ( "font format not recognized" );
      File fontFile = null;
      fontFile = File.createTempFile ( "font", ".ttf", null );Has anybody faced the same problem or an idea of how to solve this issue with little additional work?

has really nobody got an idea?

Similar Messages

  • If Statement in java.awt paint

    import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
    if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
    And then if wt is greater than max then it will say "Your overweight".
    But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
    Help much appreciated,
    Simon

    Thanks very much that works well.
    Simon
    My code now looks like this: import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void you(Graphics g)
      String statement;
      if(wt > max) statement="You are very fat";
      else if(wt < min) statement="You are very thin";
      else statement="You are in the recommended weight range for your height";
      g.drawString(statement, 20,210);
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        you(g);
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of BmiThanks again,
    Simon

  • OutOfMemory error in java.awt.image.DataBufferInt. init

    We have an applet application that performs Print Preview of the images in the canvas. The images are like a network of entities (it has pictures of the entities involve (let's say Person) and how it links to other entities). We are using IE to launch the applet.
    We set min heap space to 128MB, JVM max heap space to 256MB, java plugin max heap space to 256MB using the Control Panel > Java.
    When the canvas width is about 54860 and height is 1644 and perform Print Preview, it thows an OutOfMemoryError in java.awt.image.DataBufferInt.<int>, hence, the Print Preview page is not shown. The complete stack trace (and logs) is as follows:
    Width: 54860 H: 1644
    Max heap: 254 # using Runtime.getRuntime().maxMemory()
    javaplugin.maxHeapSize: 256M # using System.getProperties("javaplugin.maxHeapSize")
    n page x n page : 1x1
    Exception in thread "AWT-EventQueue-2" java.lang.OutOfMemoryError: Java heap space
         at java.awt.image.DataBufferInt.<init>(Unknown Source)
         at java.awt.image.Raster.createPackedRaster(Unknown Source)
         at java.awt.image.DirectColorModel.createCompatibleWritableRaster(Unknown Source)
         at java.awt.image.BufferedImage.<init>(Unknown Source)
         at com.azeus.gdi.chart.GDIChart.preparePreview(GDIChart.java:731)
         at com.azeus.gdi.chart.GDIChart.getPreview(GDIChart.java:893)
         at com.azeus.gdi.ui.GDIUserInterface.printPreviewOp(GDIUserInterface.java:1526)
         at com.azeus.gdi.ui.GDIUserInterface$21.actionPerformed(GDIUserInterface.java:1438)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Drilling down the cause of the problem. The OutOfMemory occurred in the constructor of DataBufferInt when it tried to create an int array:
    public DataBufferInt(int size) {
    super(STABLE, TYPE_INT, size);
    data = new int[size]; # this part produce out of memory error when size = width X height
    bankdata = new int[1][];
    bankdata[0] = data;
    The OutOfMemory error occurred when size is width * height (54860 X 1644) which is 90,189,840 bytes (~86MB).
    I can replicate the OutOfMemory error when initiating an int array using a test class when it uses the default max heap space but if I increase the heap space to 256MB, it cannot be replicated in the test class.
    Using a smaller width and height with product not exceeding 64MB, the applet can perform Print Preview successfully.
    Given this, I think the java applet is not using the value assigned in javaplugin.maxHeapSize to set the max heap space, hence, it still uses the default max heap size and throws OutOfMemory in int array when size exceeds the default max heap space which is 64MB.
    For additional information, below is some of the java properties (when press S in java applet console):
    browser = sun.plugin
    browser.vendor = Sun Microsystems, Inc.
    browser.version = 1.1
    java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
    java.awt.printerjob = sun.awt.windows.WPrinterJob
    java.class.path = C:\PROGRA~1\Java\jre6\classes
    java.class.version = 50.0
    java.class.version.applet = true
    java.runtime.name = Java(TM) SE Runtime Environment
    java.runtime.version = 1.6.0_17-b04
    java.specification.version = 1.6
    java.vendor.applet = true
    java.version = 1.6.0_17
    java.version.applet = true
    javaplugin.maxHeapSpace = 256M
    javaplugin.nodotversion = 160_17
    javaplugin.version = 1.6.0_17
    javaplugin.vm.options = -Xms128M -Djavaplugin.maxHeapSpace=256M -Xmx256m -Xms128M
    javawebstart.version = javaws-1.6.0_17
    Kindly advise if this is a bug in JRE or wrong setting. If wrong setting, please advise on the proper way to set the heap space to prevent OutOfMemory in initializing int array.
    Thanks a lot.
    Edited by: rei_xanther on Jun 28, 2010 12:01 AM
    Edited by: rei_xanther on Jun 28, 2010 12:37 AM

    rei_xanther wrote:
    ..But the maximum value of the int data type is 2,147,483,647. That is the maximum positive integer value that can be stored in (the 4 bytes of) a signed int, but..
    ..The value that I passed in the int array size is only 90,189,840...its only connection with RAM is that each int requires 4 bytes of memory to hold it.
    new int[size] -- size is 90,189,840Sure. So the number of bytes required to hold those 90,189,840 ints is 360,759,360.
    I assumed that one element in the int array is 1 byte. ..Your assumption is wrong. How could it be possible to store 32 bits (4 bytes) in 8 bits (1 byte)? (a)
    a) Short of some clever compression algorithm applied to the data.

  • Problem converting a (working) Java program into an applet

    When I'm trying to access an Image through a call to :
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    I'm getting a nullPointerException as a result of the call to getDocumentBase() :
    C:\Chantier\Java\BallsApplet
    AppletViewer testBallsApplet.htmljava.lang.NullPointerException
    at java.applet.Applet.getDocumentBase(Applet.java:125)
    at Balls.<init>(Balls.java:84)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    at java.lang.Class.newInstance0(Class.java:296)
    at java.lang.Class.newInstance(Class.java:249)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:548)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:477)
    at sun.applet.AppletPanel.run(AppletPanel.java:290)
    at java.lang.Thread.run(Thread.java:536)
    It seems very weird to me... :-/
    (all the .gif files are in the same directory than the .class files)
    The problem appears with AppletViewer trying to open an HTML file
    containing :
    <HTML>
    <APPLET CODE="Balls.class" WIDTH=300 HEIGHT=211>
    </APPLET>
    </HTML>
    (I tried unsuccessfully the CODEBASE and ARCHIVE attributes, with and without putting the .gif and .class into a .jar file)
    I can't find the solution by myself, so, I'd be very glad if someone could help
    me with this... Thank you very much in advance ! :-)
    You'll find below the source of a small game that I wrote and debugged (without
    problem) and that I'm now (unsuccessfully) trying to convert into an Applet :
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.URL;
    public class Balls extends java.applet.Applet implements Runnable, KeyListener
    private Image offScreenImage;
    private Image backGroundImage;
    private Image[] gifImages = new Image[6];
    private Image PressStart ;
    private Sprite pressStartSprite = null ;
    private Image YouLose ;
    private Sprite YouLoseSprite = null ;
    private Image NextStage ;
    private Sprite NextStageSprite = null ;
    private Image GamePaused ;
    private Sprite GamePausedSprite = null ;
    //offscreen graphics context
    private Graphics offScreenGraphicsCtx;
    private Thread animationThread;
    private MediaTracker mediaTracker;
    private SpriteManager spriteManager;
    //Animation display rate, 12fps
    private int animationDelay = 83;
    private Random rand = new Random(System.currentTimeMillis());
    private int message = 0 ; // 0 = no message (normal playing phase)
    // 1 = press space to start
    // 2 = press space for next level
    // 3 = game PAUSED, press space to unpause
    // 4 = You LOSE
    public static void main(String[] args)
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    }//end main
    public void start()
    //Create and start animation thread
    animationThread = new Thread(this);
    animationThread.start();
    public void init()
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    public Balls() throws java.net.MalformedURLException
    {//constructor
    // Load and track the images
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    PressStart = getImage(getDocumentBase(), "press_start.gif");
    mediaTracker.addImage(PressStart, 0);
    NextStage = getImage(getDocumentBase(), "stage_complete.gif");
    mediaTracker.addImage(NextStage, 0);
    GamePaused = getImage(getDocumentBase(), "game_paused.gif");
    mediaTracker.addImage(GamePaused, 0);
    YouLose = getImage(getDocumentBase(), "you_lose.gif");
    mediaTracker.addImage(YouLose, 0);
    //Get and track 6 images to use
    // for sprites
    gifImages[0] = getImage(getDocumentBase(), "blueball.gif");
    mediaTracker.addImage(gifImages[0], 0);
    gifImages[1] = getImage(getDocumentBase(), "redball.gif");
    mediaTracker.addImage(gifImages[1], 0);
    gifImages[2] = getImage(getDocumentBase(), "greenball.gif");
    mediaTracker.addImage(gifImages[2], 0);
    gifImages[3] = getImage(getDocumentBase(), "yellowball.gif");
    mediaTracker.addImage(gifImages[3], 0);
    gifImages[4] = getImage(getDocumentBase(), "purpleball.gif");
    mediaTracker.addImage(gifImages[4], 0);
    gifImages[5] = getImage(getDocumentBase(), "orangeball.gif");
    mediaTracker.addImage(gifImages[5], 0);
    //Block and wait for all images to
    // be loaded
    try {
    mediaTracker.waitForID(0);
    }catch (InterruptedException e) {
    System.out.println(e);
    }//end catch
    //Base the Frame size on the size
    // of the background image.
    //These getter methods return -1 if
    // the size is not yet known.
    //Insets will be used later to
    // limit the graphics area to the
    // client area of the Frame.
    int width = backGroundImage.getWidth(this);
    int height = backGroundImage.getHeight(this);
    //While not likely, it may be
    // possible that the size isn't
    // known yet. Do the following
    // just in case.
    //Wait until size is known
    while(width == -1 || height == -1)
    System.out.println("Waiting for image");
    width = backGroundImage.getWidth(this);
    height = backGroundImage.getHeight(this);
    }//end while loop
    //Display the frame
    setSize(width,height);
    setVisible(true);
    //setTitle("Balls");
    //Anonymous inner class window
    // listener to terminate the
    // program.
    this.addWindowListener
    (new WindowAdapter()
    {public void windowClosing(WindowEvent e){System.exit(0);}});
    // Add a key listener for keyboard management
    this.addKeyListener(this);
    }//end constructor
    public void run()
    Point center_place = new Point(
    backGroundImage.getWidth(this)/2-PressStart.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-PressStart.getHeight(this)/2) ;
    pressStartSprite = new Sprite(this, PressStart, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-NextStage.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-NextStage.getHeight(this)/2) ;
    NextStageSprite = new Sprite(this, NextStage, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-GamePaused.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-GamePaused.getHeight(this)/2) ;
    GamePausedSprite = new Sprite(this, GamePaused, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-YouLose.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-YouLose.getHeight(this)/2) ;
    YouLoseSprite = new Sprite(this, YouLose, center_place, new Point(0, 0),true);
    BackgroundImage bgimage = new BackgroundImage(this, backGroundImage) ;
    for (;;) // infinite loop
    long time = System.currentTimeMillis();
    message = 1 ; // "press start to begin"
    while (message != 0)
    repaint() ;
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    boolean you_lose = false ;
    for (int max_speed = 7 ; !you_lose && max_speed < 15 ; max_speed++)
    for (int difficulty = 2 ; !you_lose && difficulty < 14 ; difficulty++)
    boolean unfinished_stage = true ;
    spriteManager = new SpriteManager(bgimage);
    spriteManager.setParameters(difficulty, max_speed) ;
    //Create 15 sprites from 6 gif
    // files.
    for (int cnt = 0; cnt < 15; cnt++)
    if (cnt == 0)
    Point position = new Point(
    backGroundImage.getWidth(this)/2-gifImages[0].getWidth(this)/2,
    backGroundImage.getHeight(this)/2-gifImages[0].getHeight(this)/2) ;
    spriteManager.addSprite(makeSprite(position, 0, false));
    else
    Point position = spriteManager.
    getEmptyPosition(new Dimension(gifImages[0].getWidth(this),
    gifImages[0].getHeight(this)));
    if (cnt < difficulty)
    spriteManager.addSprite(makeSprite(position, 1, true));
    else
    spriteManager.addSprite(makeSprite(position, 2, true));
    }//end for loop
    time = System.currentTimeMillis();
    while (!spriteManager.getFinishedStage() && !spriteManager.getGameOver())
    // Loop, sleep, and update sprite
    // positions once each 83
    // milliseconds
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    }//end while loop
    if (spriteManager.getGameOver())
    message = 4 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    you_lose = true ;
    if (spriteManager.getFinishedStage())
    message = 2 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    } // end for difficulty loop
    } // end for max_speed
    } // end infinite loop
    }//end run method
    private Sprite makeSprite(Point position, int imageIndex, boolean wind)
    return new Sprite(
    this,
    gifImages[imageIndex],
    position,
    new Point(rand.nextInt() % 5,
    rand.nextInt() % 5),
    wind);
    }//end makeSprite()
    //Overridden graphics update method
    // on the Frame
    public void update(Graphics g)
    //Create the offscreen graphics
    // context
    if (offScreenGraphicsCtx == null)
    offScreenImage = createImage(getSize().width,
    getSize().height);
    offScreenGraphicsCtx = offScreenImage.getGraphics();
    }//end if
    if (message == 0)
    // Draw the sprites offscreen
    spriteManager.drawScene(offScreenGraphicsCtx);
    else if (message == 1)
    pressStartSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 2)
    NextStageSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 3)
    GamePausedSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 4)
    YouLoseSprite.drawSpriteImage(offScreenGraphicsCtx);
    // Draw the scene onto the screen
    if(offScreenImage != null)
    g.drawImage(offScreenImage, 0, 0, this);
    }//end if
    }//end overridden update method
    //Overridden paint method on the
    // Frame
    public void paint(Graphics g)
    //Nothing required here. All
    // drawing is done in the update
    // method above.
    }//end overridden paint method
    // Methods to handle Keyboard event
    public void keyPressed(KeyEvent evt)
    int key = evt.getKeyCode(); // Keyboard code for the pressed key.
    if (key == KeyEvent.VK_SPACE)
    if (message != 0)
    message = 0 ;
    else
    message = 3 ;
    if (key == KeyEvent.VK_LEFT)
    if (spriteManager != null)
    spriteManager.goLeft() ;
    else if (key == KeyEvent.VK_RIGHT)
    if (spriteManager != null)
    spriteManager.goRight() ;
    else if (key == KeyEvent.VK_UP)
    if (spriteManager != null)
    spriteManager.goUp() ;
    else if (key == KeyEvent.VK_DOWN)
    if (spriteManager != null)
    spriteManager.goDown() ;
    if (spriteManager != null)
    spriteManager.setMessage(message) ;
    public void keyReleased(KeyEvent evt)
    public void keyTyped(KeyEvent e)
    char key = e.getKeyChar() ;
    //~ if (key == 's')
    //~ stop = true ;
    //~ else if (key == 'c')
    //~ stop = false ;
    //~ spriteManager.setStop(stop) ;
    }//end class Balls
    //===================================//
    class BackgroundImage
    private Image image;
    private Component component;
    private Dimension size;
    public BackgroundImage(
    Component component,
    Image image)
    this.component = component;
    size = component.getSize();
    this.image = image;
    }//end construtor
    public Dimension getSize(){
    return size;
    }//end getSize()
    public Image getImage(){
    return image;
    }//end getImage()
    public void setImage(Image image){
    this.image = image;
    }//end setImage()
    public void drawBackgroundImage(Graphics g)
    g.drawImage(image, 0, 0, component);
    }//end drawBackgroundImage()
    }//end class BackgroundImage
    //===========================
    class SpriteManager extends Vector
    private BackgroundImage backgroundImage;
    private boolean finished_stage = false ;
    private boolean game_over = false ;
    private int difficulty ;
    private int max_speed ;
    public boolean getFinishedStage()
    finished_stage = true ;
    for (int cnt = difficulty ; cnt < size(); cnt++)
    Sprite sprite = (Sprite)elementAt(cnt);
    if (!sprite.getEaten())
    finished_stage = false ;
    return finished_stage ;
    public boolean getGameOver() {return game_over ;}
    public void setParameters(int diff, int speed)
    difficulty = diff ;
    max_speed = speed ;
    finished_stage = false ;
    game_over = false ;
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    sprite.setSpeed(max_speed) ;
    public SpriteManager(BackgroundImage backgroundImage)
    this.backgroundImage = backgroundImage ;
    }//end constructor
    public Point getEmptyPosition(Dimension spriteSize)
    Rectangle trialSpaceOccupied = new Rectangle(0, 0,
    spriteSize.width,
    spriteSize.height);
    Random rand = new Random(System.currentTimeMillis());
    boolean empty = false;
    int numTries = 0;
    // Search for an empty position
    while (!empty && numTries++ < 100)
    // Get a trial position
    trialSpaceOccupied.x =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().width);
    trialSpaceOccupied.y =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().height);
    // Iterate through existing
    // sprites, checking if position
    // is empty
    boolean collision = false;
    for(int cnt = 0;cnt < size(); cnt++)
    Rectangle testSpaceOccupied = ((Sprite)elementAt(cnt)).getSpaceOccupied();
    if (trialSpaceOccupied.intersects(testSpaceOccupied))
    collision = true;
    }//end if
    }//end for loop
    empty = !collision;
    }//end while loop
    return new Point(trialSpaceOccupied.x, trialSpaceOccupied.y);
    }//end getEmptyPosition()
    public void update()
    Sprite sprite;
    // treat special case of sprite #0 (the player)
    sprite = (Sprite)elementAt(0);
    sprite.updatePosition() ;
    int hitIndex = testForCollision(sprite);
    if (hitIndex != -1)
    if (hitIndex < difficulty)
    { // if player collides with an hunter (red ball), he loose
    sprite.setEaten() ;
    game_over = true ;
    else
    // if player collides with an hunted (green ball), he eats the green
    ((Sprite)elementAt(hitIndex)).setEaten() ;
    //Iterate through sprite list
    for (int cnt = 1;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's position
    sprite.updatePosition();
    //Test for collision. Positive
    // result indicates a collision
    hitIndex = testForCollision(sprite);
    if (hitIndex >= 0)
    //a collision has occurred
    bounceOffSprite(cnt,hitIndex);
    }//end if
    }//end for loop
    }//end update
    public void setMessage(int message)
    Sprite sprite;
    //Iterate through sprite list
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's stop status
    sprite.setMessage(message);
    }//end for loop
    }//end update
    public void goLeft()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goLeft() ;
    public void goRight()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goRight() ;
    public void goUp()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goUp() ;
    public void goDown()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goDown() ;
    private int testForCollision(Sprite testSprite)
    //Check for collision with other
    // sprites
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    if (sprite == testSprite)
    //don't check self
    continue;
    //Invoke testCollision method
    // of Sprite class to perform
    // the actual test.
    if (testSprite.testCollision(sprite))
    //Return index of colliding
    // sprite
    return cnt;
    }//end for loop
    return -1;//No collision detected
    }//end testForCollision()
    private void bounceOffSprite(int oneHitIndex, int otherHitIndex)
    //Swap motion vectors for
    // bounce algorithm
    Sprite oneSprite = (Sprite)elementAt(oneHitIndex);
    Sprite otherSprite = (Sprite)elementAt(otherHitIndex);
    Point swap = oneSprite.getMotionVector();
    oneSprite.setMotionVector(otherSprite.getMotionVector());
    otherSprite.setMotionVector(swap);
    }//end bounceOffSprite()
    public void drawScene(Graphics g)
    //Draw the background and erase
    // sprites from graphics area
    //Disable the following statement
    // for an interesting effect.
    backgroundImage.drawBackgroundImage(g);
    //Iterate through sprites, drawing
    // each sprite
    for (int cnt = 0;cnt < size(); cnt++)
    ((Sprite)elementAt(cnt)).drawSpriteImage(g);
    }//end drawScene()
    public void addSprite(Sprite sprite)
    addElement(sprite);
    }//end addSprite()
    }//end class SpriteManager
    //===================================//
    class Sprite
    private Component component;
    private Image image;
    private Rectangle spaceOccupied;
    private Point motionVector;
    private Rectangle bounds;
    private Random rand;
    private int message = 0 ; // number of message currently displayed (0 means "no message" = normal game)
    private int max_speed = 7 ;
    private boolean eaten = false ; // when a green sprite is eaten, it is no longer displayed on screen
    private boolean wind = true ;
    private boolean go_left = false ;
    private boolean go_right = false ;
    private boolean go_up = false ;
    private boolean go_down = false ;
    public Sprite(Component component,
    Image image,
    Point position,
    Point motionVector,
    boolean Wind
    //Seed a random number generator
    // for this sprite with the sprite
    // position.
    rand = new Random(position.x);
    this.component = component;
    this.image = image;
    setSpaceOccupied(new Rectangle(
    position.x,
    position.y,
    image.getWidth(component),
    image.getHeight(component)));
    this.motionVector = motionVector;
    this.wind = Wind ;
    //Compute edges of usable graphics
    // area in the Frame.
    int topBanner = ((Container)component).getInsets().top;
    int bottomBorder = ((Container)component).getInsets().bottom;
    int leftBorder = ((Container)component).getInsets().left;
    int rightBorder = ((Container)component).getInsets().right;
    bounds = new Rectangle( 0 + leftBorder, 0 + topBanner
    , component.getSize().width - (leftBorder + rightBorder)
    , component.getSize().height - (topBanner + bottomBorder));
    }//end constructor
    public void setMessage(int message_number)
    message = message_number ;
    public void setSpeed(int speed)
    max_speed = speed ;
    public void goLeft()
    go_left = true ;
    public void goRight()
    go_right = true ;
    public void goUp()
    go_up = true ;
    public void goDown()
    go_down = true ;
    public void setEaten()
    eaten = true ;
    setSpaceOccupied(new Rectangle(4000,4000,0,0)) ;
    public boolean getEaten()
    return eaten ;
    public Rectangle getSpaceOccupied()
    return spaceOccupied;
    }//end getSpaceOccupied()
    void setSpaceOccupied(Rectangle spaceOccupied)
    this.spaceOccupied = spaceOccupied;
    }//setSpaceOccupied()
    public void setSpaceOccupied(
    Point position){
    spaceOccupied.setLocation(
    position.x, position.y);
    }//setSpaceOccupied()
    public Point getMotionVector(){
    return motionVector;
    }//end getMotionVector()
    public void setMotionVector(
    Point motionVector){
    this.motionVector = motionVector;
    }//end setMotionVector()
    public void setBounds(Rectangle bounds)
    this.bounds = bounds;
    }//end setBounds()
    public void updatePosition()
    Point position = new Point(spaceOccupied.x, spaceOccupied.y);
    if (message != 0)
    return ;
    //Insert random behavior. During
    // each update, a sprite has about
    // one chance in 10 of making a
    // random change to its
    // motionVector. When a change
    // occurs, the motionVector
    // coordinate values are forced to
    // fall between -7 and 7. This
    // puts a cap on the maximum speed
    // for a sprite.
    if (!wind)
    if (go_left)
    motionVector.x -= 2 ;
    if (motionVector.x < -15)
    motionVector.x = -14 ;
    go_left = false ;
    if (go_right)
    motionVector.x += 2 ;
    if (motionVector.x > 15)
    motionVector.x = 14 ;
    go_right = false ;
    if (go_up)
    motionVector.y -= 2 ;
    if (motionVector.y < -15)
    motionVector.y = -14 ;
    go_up = false ;
    if (go_down)
    motionVector.y += 2 ;
    if (motionVector.y > 15)
    motionVector.y = 14 ;
    go_down = false ;
    else if(rand.nextInt() % 7 == 0)
    Point randomOffset =
    new Point(rand.nextInt() % 3,
    rand.nextInt() % 3);
    motionVector.x += randomOffset.x;
    if(motionVector.x >= max_speed)
    motionVector.x -= max_speed;
    if(motionVector.x <= -max_speed)
    motionVector.x += max_speed ;
    motionVector.y += randomOffset.y;
    if(motionVector.y >= max_speed)
    motionVector.y -= max_speed;
    if(motionVector.y <= -max_speed)
    motionVector.y += max_speed;
    }//end if
    //Move the sprite on the screen
    position.translate(motionVector.x, motionVector.y);
    //Bounce off the walls
    boolean bounceRequired = false;
    Point tempMotionVector = new Point(
    motionVector.x,
    motionVector.y);
    //Handle walls in x-dimension
    if (position.x < bounds.x)
    bounceRequired = true;
    position.x = bounds.x;
    //reverse direction in x
    tempMotionVector.x = -tempMotionVector.x;
    else if ((position.x + spaceOccupied.width) > (bounds.x + bounds.width))
    bounceRequired = true;
    position.x = bounds.x +
    bounds.width -
    spaceOccupied.width;
    //reverse direction in x
    tempMotionVector.x =
    -tempMotionVector.x;
    }//end else if
    //Handle walls in y-dimension
    if (position.y < bounds.y)
    bounceRequired = true;
    position.y = bounds.y;
    tempMotionVector.y = -tempMotionVector.y;
    else if ((position.y + spaceOccupied.height)
    > (bounds.y + bounds.height))
    bounceRequired = true;
    position.y = bounds.y +
    bounds.height -
    spaceOccupied.height;
    tempMotionVector.y =
    -tempMotionVector.y;
    }//end else if
    if(bounceRequired)
    //save new motionVector
    setMotionVector(
    tempMotionVector);
    //update spaceOccupied
    setSpaceOccupied(position);
    }//end updatePosition()
    public void drawSpriteImage(Graphics g)
    if (!eaten)
    g.drawImage(image,
    spaceOccupied.x,
    spaceOccupied.y,
    component);
    }//end drawSpriteImage()
    public boolean testCollision(Sprite testSprite)
    //Check for collision with
    // another sprite
    if (testSprite != this)
    return spaceOccupied.intersects(
    testSprite.getSpaceOccupied());
    }//end if
    return false;
    }//end testCollision
    }//end Sprite class
    //===================================//
    Thanks for your help...

    Sorry,
    Can you tell me how do you solve it because I have got the same problem.
    Can you indicate me the topic where did you find solution.
    Thank in advance.

  • Java.awt.Container.add(Container.java:345) how can i handle this

    dear all,
    i want to design an outlook for a chat applet. but this seems to tough as i am getting a run time error
    my code is:
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    * the import that are required for this class
    public class outer extends Frame //implements ActionListener, Runnable
    private TextField txtusername,txtpassword,txtroomname;
    private Label lblusername,lblpassword,lblroomname,lbllistofrooms;
    Button okBtn,exitBut;
    Color backColor=null,btnBackClr=null,btnForeClr=null;
    String[] roomsavailable = {" one ", " two ", " three", " four"};
    private JList rooms = new JList(roomsavailable);
    /** the costructor*/
    public outer()
    { // super(st);
    backColor=new Color(200,200,255);
    btnBackClr=new Color(225,240,255);
    btnForeClr=new Color(205,205,205);
    setBackground(backColor);
    setLayout(null);
    lblusername = new Label("Username");
    lblusername.reshape(insets().left+5,insets().top+10,60,20);
    add(lblusername);
    txtusername=new TextField();
    txtusername.reshape(insets().left+75,insets().top+10,60,20);
    add(txtusername);
    lblpassword = new Label("Password");
    lblpassword.reshape(insets().left+5,insets().top+30,60,20);
    add(lblpassword);
    txtpassword=new TextField();
    txtpassword.reshape(insets().left+75,insets().top+30,60,20);
    add(txtpassword);
    lblroomname = new Label("Select Room");
    lblroomname.reshape(insets().left+5,insets().top+50,60,20);
    add(lblroomname);
    txtroomname=new TextField();
    txtroomname.reshape(insets().left+75,insets().top+50,60,20);
    add(txtroomname);
    okBtn=new Button("Login");
    okBtn.reshape(insets().left+25,insets().top+80,60,20);
    add(okBtn);
    // okBtn.addActionListener(this);
    exitBut=new Button("EXIT");
    exitBut.reshape(insets().left+50,insets().top+80,60,20);
    add(exitBut);
    // exitBut.addActionListener(this);
    public static void main(String[] args)
    // Create a JFrame
    JFrame frame = new JFrame("client side");
    // Create a outer class object
    outer outerobj = new outer();
    // Add the outer to the JFrame
    frame.getContentPane().add(outerobj, BorderLayout.WEST);
    // Set Jframe size
    frame.setSize(800, 400);
    //set resizable true
    frame.setResizable(true);
    // Set JFrame to visible
    frame.setVisible(true);
    // set the close operation so that the Application terminates when closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    when i compile it it compiles but gives run time error like this
    RUN TIME error:
    Exception in thread "main" java.lang.IllegalArgumentException: adding a window
    to a container
    at java.awt.Container.addImpl(Container.java:434)
    at java.awt.Container.add(Container.java:345)
    at outer.main(outer.java:75)
    Press any key to continue...
    i know erroe in this line
    frame.getContentPane().add(outerobj, BorderLayout.WEST);
    but how shall i add to get the proper layout by getting benifit of insets method
    reply soon
    please

    You can't add a frame to a frame.
    Try chaing the class definition from
    public class outer extends Frameto
    public class outer extends PanelPlease note to format your code (you'll get a faster response) use [ code]
    Object names should always start with a capital letter. outer --> Outer

  • Java.awt availability in CDC Toolkit ?

    Hi guys and girls,
    I've just tried out the Sun Java Toolkit for CDC 1.0 .. I tried making a simple app which uses awt components, such as Frame, Label, Button .. but the Label and Button just wont compile. I always thought that CDC has all the lib for the j2se's java.awt.
    Quoted from CDC FAQ :
    CDC currently supports three profiles. Foundation Profile provides basic application support APIs without any additional support for GUIs. Personal Basis Profile includes all of the APIs contained in Foundation Profile and adds support for lightweight AWT GUI components and the xlet application model. Personal Profile includes all of the APIs contained in Personal Basis Profile and adds support for full AWT compatibility and the applet application model.
    Do i miss something .. ? Please help pointing out for me ..
    I understand that there's swing from the AGui. So i tried making a new project with a simple class containing a simple JFrame, containing a JPanel which contains a button, which can be clicked to trigger a message type JOptionPane. But when the JOptionPane appears, it fills up the entire screen, i dont quite understand what is wrong.
    Here's the code :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class HelloWorld {
          * @param args
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Ahiak");
              final JPanel panel = new JPanel(new FlowLayout());
              JButton but = new JButton("Click Me !");
              panel.add(but);
              frame.getContentPane().add(panel);
              but.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(panel, "hahah !");
              frame.setVisible(true);
    }Please show some compassion and click the reply button, lol -_-                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I don't know about swing, but you can try using AWT and compile it with J2SE (set compliance to 1.4). The jar file should work on your mobile device with Personal Profile.

  • Cannot resolve symbol java.awt.graphics

    // DrawRectangleDemo.java
    import java.awt.*;
    import java.lang.Object;
    import java.applet.Applet;
    public class DrawRectangleDemo extends Applet
         public void paint (Graphics g)
              // Get the height and width of the applet's drawing surface.
              int width = getSize ().width;
              int height = getSize ().height;
              int rectWidth = (width-50)/3;
              int rectHeight = (height-70)/2;
              int x = 5;
              int y = 5;
              g.drawRect (x, y, rectWidth, rectHeight);
              g.drawString ("drawRect", x, rectHeight + 30);
              x += rectWidth + 20;
              g.fillRect (x, y, rectWidth, rectHeight);
              // Calculate a border area with each side equal tp 25% of
              // the rectangle's width.
              int border = (int) (rectWidth * 0.25);
              // Clear 50% of the filled rectangle.
              g.clearRect (x + border, y + border,
                             rectWidth - 2 * border, rectHeight - 2 * border);
              g.drawString ("fillRect/clearRect", x, rectHeight + 30);
              x += rectWidth + 20;
              g.drawRoundRect (x, y, rectWidth, rectHeight, 15, 15);
              g.drawString ("drawRoundRect", x, rectHeight + 30);
              x=5;
              y += rectHeight + 40;
              g.setColor (Color.yellow);
              for (int i = 0; i < 4; i++)
                   g.draw3DRect (x + i * 2, y + i * 2,
                                       rectWidth - i * 4, rectHeight - i * 4, false);
              g.setColor (Color.black);
              g.drawString ("draw3DRect", x, y, + rectHeight + 25);
              x += rectWidth + 20;
              g.setColor (Color.yellow);
              g.fill3DRect (x, y, rectWidth, rectHeight, true);
              g.setColor (Color.black);
              g.drawString ("fill3DRect", x, y, + rectHeight + 25);
    Help me with this codes. I typed correctly but there still errors.
    --------------------Configuration: JDK version 1.3.1 <Default>--------------------
    D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:56: cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    location: class java.awt.Graphics
              g.drawString ("draw3DRect", x, y, + rectHeight + 25);
    ^
    D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:64: cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    location: class java.awt.Graphics
              g.drawString ("fill3DRect", x, y, + rectHeight + 25);
    ^
    2 errors
    Process completed.
    -------------------------------------------------------------------------------------------------------------------------------

    cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    This is telling you that you are trying to invoke the drawString() method with 4 parameters: String, int, int, int
    If you look at the API the drawString() method need 3 parameters: String, int, int - so you have an extra int
    location: class java.awt.Graphics
    g.drawString ("draw3DRect", x, y, + rectHeight + 25);
    Now is you look at your code you will find that you have 3 ',' in you method call. (I don't think you want the ',' after the y.

  • Java.lang.NoSuchMethodError:sun.applet.AppletPanel.changeFrameAppContext

    What does this mean?
    java.lang.NoSuchMethodError:sun.applet.AppletPanel.changeFrameAppContext(Ljava/awt/Frame;Lsun/awt/AppContext;)V
         at sun.plugin.viewer.IExplorerPluginObject.appletStateChanged(Unknown Source)
         at sun.applet.AppletEventMulticaster.appletStateChanged(AppletEventMulticaster.java:32)
         at sun.applet.AppletPanel.dispatchAppletEvent(AppletPanel.java:233)
         at sun.applet.AppletPanel.runLoader(AppletPanel.java:532)
         at sun.applet.AppletPanel.run(AppletPanel.java:293)
         at java.lang.Thread.run(Thread.java:536)
    and where does it occur?
    thanks in advance, ulrich

    I've started seeing this as well since installing 1.4.2. Anyone have any ideas on this?
    What does this mean?
    java.lang.NoSuchMethodError:sun.applet.AppletPanel.chan
    eFrameAppContext(Ljava/awt/Frame;Lsun/awt/AppContext;)V
    at
    sun.plugin.viewer.IExplorerPluginObject.appletStateCha
    ged(Unknown Source)
    at
    sun.applet.AppletEventMulticaster.appletStateChanged(A
    pletEventMulticaster.java:32)
    at
    sun.applet.AppletPanel.dispatchAppletEvent(AppletPanel
    java:233)
    at
    sun.applet.AppletPanel.runLoader(AppletPanel.java:532)
         at sun.applet.AppletPanel.run(AppletPanel.java:293)
         at java.lang.Thread.run(Thread.java:536)
    and where does it occur?
    thanks in advance, ulrich

  • Java.io.NotSerializableException: java.awt.AWTEventMulticaster

    I have an Applet. When I try to use the "print" feature on IE to print out the applet. I'm getting this Exception. java.io.NotSerializableException: java.awt.AWTEventMulticaster
    What should I do?
    Andy

    please help!!

  • Significance of "You need to enable Java to see this applet"

    i am a novish for applet programming.
    i have written the code for drawing a spectrum.
    import java.applet.*;
    import java.awt.*;
    public class DrawingWithColor1 extends Applet {
    int width, height;
    int N = 25; // the number of colors created
    Color[] spectrum; // an array of elements, each of type Color
    Color[] spectrum2; // another array
    public void init() {
    width = getSize().width;
    height = getSize().height;
    setBackground( Color.black );
    // Allocate the arrays; make them "N" elements long
    spectrum = new Color[ N ];
    spectrum2 = new Color[ N ];
    // Generate the colors and store them in the arrays.
    for ( int i = 1; i <= N; ++i ) {
    // The three numbers passed to the Color() constructor
    // are RGB components in the range [0,1].
    // The casting to (float) is done so that the divisions will be
    // done with floating point numbers, yielding fractional quotients.
    // As i goes from 1 to N, this color goes from almost black to white.
    spectrum[ i-1 ] = new Color( i/(float)N, i/(float)N, i/(float)N );
    // As i goes from 1 to N, this color goes from almost pure green to pure red.
    spectrum2[ i-1 ] = new Color( i/(float)N, (N-i)/(float)N, 0 );
    public void paint( Graphics g ) {
    int step = 90 / N;
    for ( int i = 0; i < N; ++i ) {
    g.setColor( spectrum[ i ] );
    g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 );
    g.setColor( spectrum2[ i ] );
    g.fillArc( width/3, height/3, 4*width/3, 4*height/3, 90+i*step, step+1 );
    Then it is requires to enable java to see this applet.
    i went to intenet explorer->tools->internet options->advanced->enabled jre(sun)and ok
    Please help me how to proceed further to view the final output

    If you're using Microsoft's JVM, I think you have to restart the browser after turning the JVM on.
    But it's an old, crappy JVM anyway.
    Install the Java plug-in from Sun.

  • Can I build a GUI application with SWING only without [import java.awt.*;]

    I have seen several threads (in forums), books and tutorials about SWING and I see that they all mix SWING with AWT (I mean they import both Swing and AWT in their code).
    The conclusion that comes out is:
    It is good to learn about SWING and forget AWT as it won't be supported later. I have decided to do so, and I never include <<import java.awt.*;>> in my code.
    But I see that you cannot do much without <<import java.awt.*;>>. For example this line which changes the background color:
    <<frame.getContentPane().setBackground(Color.red)>>
    works only with <<import java.awt.*;>>. I have seen that codes in this and other forums import awt to change the background. Why is that?
    After all, I wonder, what can I do;
    My question is, can I change the background (and of course do all other things listener, buttons etc) without using <<import java.awt.*;>>.
    I would like to avoid using <<import java.awt.*;>> and using awt since my program will not work later.
    In addition, I believe there is no point to learn awt, which later will not exist.
    I know, I must have misunderstood something. I would appreceate it very much, if anyone could give me even a short answer.
    Thank you in advance,
    JMelsi

    Since swing is a layer on top of awt, AWT will exist for as long as swing does.
    If sun does ever remove AWT they will have to replace it something else swing can layer on to and you will probably only have to replace your import statements.
    The main difference is the way there drawn to the screen.
    You can do custom drawing on swing components but you can't on AWT.
    If your using a desktop PC system it's probably best to use swing just in case you wish to do some custom drawing.
    awt uses less memory than swing and is faster but swing can be extended. awt comes only as standard.
    Say for example you wish to implement a JButton with a ProgressBar below the button text, this can be done with swing!

  • The method add() in java.awt.Container made me in confuse

    Here is my two java code file:
    //MyContainer.java
    package sam.gui;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    public class MyContainer extends JApplet {
         private MyButton[] myButton = new MyButton[2];
         private static int counter = 0;
         public MyContainer() {
              myButton[0] = new MyButton(5, 5, 200, 30);
              myButton[1] = new MyButton(5, 40, 200, 30);
              for (int i = 0; i < myButton.length; i++) {
                   add(myButton);
         public void paint(Graphics g) {
              for (int i = 0; i < myButton.length; i++) {
                   System.out.println("MyButton : " + (i+1));
                   myButton[i].draw(g);
         public static void main(String[] args) {
              MyContainer container = new MyContainer();
              JFrame f = new JFrame();
              f.getContentPane().add(container);
              f.pack();
              f.setSize(new Dimension(300, 200));
              f.show();
    //MyButton.java
    package sam.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class MyButton extends Component {
         private Color m_rectColor = new Color(128, 73, 0);
         public MyButton(int x, int y, int width, int height) {
              setBounds(x, y, width, height);     
         public void draw(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              g.setColor(m_rectColor);
              g.fillRect(0, 0,
                        getBounds().width, getBounds().height);
              System.out.println("x = " + getBounds().x);
              System.out.println("y = " + getBounds().y);
              System.out.println("width = " + getBounds().width);
              System.out.println("height = " + getBounds().height);          
    I thinked the runned result should be below:
    MyButton : 1
    x = 5
    y = 5
    width = 200
    height = 30
    MyButton : 2
    x = 5
    y = 40
    width = 200
    height = 30But in fact, its result is here:
    MyButton : 1
    x = 5
    y = 5
    width = 200
    height = 30
    MyButton : 2
    x = 0
    y = 0
    width = 292
    height = 173I don't know why the result would like this? I have used add(...) method to add two component MyButton to the container MyContainer, But the bounds of the second component is not I want.
    So this problem made me go into confuse.

    You need to learn how layout managers work. The default layout manager of a JApplet and JFrame is BorderLayout .
    /Kaj

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Useless code in java.awt.image.SampleModel.java?

    Hey there,
    i just looked up the sourcecode of java.awt.image.SampleModel.java in JDK 6
    I discovered two issues i'd like to discuss.
    1) on lines 736 to 739 this code is stated:
    if (iArray != null)
    pixels = iArray;
    else
    pixels = new int[numBands * w * h];
    I asked myself, why does this code exist? while the getPixels() method is overwritten twice by double[] getPixels() and float[] getPixels, it is impossible to reach the part of the java code that initializes the pixels-array. One could only step into that line if "null" is given for the i/d/fArray-parameter. but if one would do so, the Java parser couldn't determine, which method is to use. so this part of code is just useless IMHO.
    the java developers could get a little more performance out of this method if the if statement would be cut out - especially when reading a lot of very small rasters
    or, on the other hand, they could replace this piece of code by an explicit bounds check.
    When somebody touches this code, i would appreciate it if the errormessage "index out of bounds!" could be rewritten to be a little more verbose, like: Index out of bounds(x=123; y=456, maxX=100, maxY=400)!(numbers are just examples)
    I hope i didn't miss something very basic and could help improving this class a little bit.
    2) the local variable Offset(line 734) is coded against code conventions which say, variables shall start with a lowercase letter. Offset obviously doesn't fit that convention.
    best regards
    kdot

    One could only step into that line if "null" is given for the i/d/fArray-parameter. but if one would do so, the Java parser couldn't determine, which method is to use. so this part of code is just useless IMHO. You can have
    sampleModel.getPixels(x,y,w,h,(int[]) null, dataBuffer);No ambiguity on which method to use.
    the local variable Offset(line 734) is coded against code conventions which say, variables shall start with a lowercase letter. Offset obviously doesn't fit that convention. You're correct, offset is against coding conventions. So are many other examples scattered throughout the jdk source code. For example, Hashtable should be called HashTable. In some cases the coding conventions might not have been established when the original code was written. In other cases it might have been human error. In yet other cases the conventions were probably ignored. The person who wrote the SampleModel class did so some 10+ years ago (Java 1.2). Who knows what he/she was thinking at the time, and in all honesty - does it really matter in this case?
    Did you know there are some classes that declare unused local variables (ahem ColorConvertOp)? Some also have unused imports ( *** cough *** BufferedImage *** cough *** ). In essence, the jdk source code is not the epidemy of code correctness. But it's still pretty good.

Maybe you are looking for

  • Torch Select Button Doesn't Work with Keyboard Out

    Hi there, need some help. Just recently (2 wks) the middle select button has quit working on my torch when I have the keyboard extended.  I can still scroll around the screen with it, but when I push it to "select" it does nothing.  The button works

  • Tt_open() Fail, no Error code too.. from solaris 10 x86  to solaris 8 spac

    when i try remote tt_open() alway fail. in solaris10 x86 between solaris10 x86 and solaris8 spac. it is version problem? but strange one is solaris8-spac can be open to solaris10-x86. this is my test list. 1. solaris 8(spac) can be tt_open() to solar

  • HTML export Issue

    HTML export used to export a functional interactive file I could open in Safari. Now it doesn't. Cause appears to be changing html extension to .wdgt (for iBook Author) and then changing it back again,the file ceased to work and prevented any other e

  • How to know if iam in tcode  creation or modif  inside abap  prog ?

    hello , i  want  to  know if there  is any things  that can  help  me to know  if  iam  in tcode  of creation (ME21N) o  modification (ME22N/ME23N) for  PO,  without using  sy-tcode inside a program of smartforms edition. thanks , karim

  • Why can't  I find SHUFFLE when selecting Genre in ios7

    WHAT the heck???  I can't find the shuffle function using itunes when choosing GENRE!!!.  For crying out loud.  How could they mess this up?  Does no one test this stuff before releasing.  Anyone know a way to do it.  What am I missing??????