Flickering in applets

Hi
I have this problem. My applet flickers everytime I scroll down the page. I have used update(Graphics). What do I do about this?
Thanks

the problem is that u make a huge image processing in the paint or update method like
Graphics offScreenGraphics = offScreenImage.getGraphics();
offScreenGraphics.setColor(getBackground());
offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
offScreenGraphics.setColor(g.getColor());
so put them in Init() method in any place of your code
then make the image processing you want, for example draw you game interface to the offScreenGraphics variable
after that use the method paint(Graphics g)
just to draw your "offScreenImage" to applet graphics
this for sure will distribute the time and effort of your graphics processing over many parts of your code
and for flickering when scrolling, scroll makes your app call the paint(Graphics g) method, and it will flicker for ever except if made
an advanced high level code that can get the region of your graphics surface to update, example just update Rectangle (10,10,50,50) not all the Rectangle(0,0,500,500)
to do this see some topics in java 2D, 3D or game programming, or java advanced imaging APIs those are more concerned of the fast processing and high quality image presenting on screen.
hope this help,
mnmmm

Similar Messages

  • Paint(), update(), reducing flickering of applets.., not repaint()ing

    I made an applet which moves a square from one end to other end, but i used the public void paint(Graphics c)
    To reduce flickering one has to use the update() in place of paint() and call paint() at the end...well, when i do this the update() method doesnt repaint...
    Heres the code..
    import java.awt.*;
    import java.applet.*;
              public class appAniBox extends Applet implements Runnable{
                   int x = 0;
                                       public void init(){
                                            Thread t = new Thread(this);
                                                 t.start();
                                  public void run(){
                                       for(;;){
                                                 repaint();
                                                 try{
                                                 Thread.sleep(6);
                                            catch(Exception e){ }
                                       [u]public void update(Graphics g){
                                            g.setColor(Color.green);
                                                 g.fillRect(x,50,50,50);
                                                 x ++;
                                                 super.paint(g);
                                                 }[/u]                                             
              //<applet code = appAniBox height = 150 width = 700></applet>

    handy-dandy double buffering code...
    // Usage
    DoubleBuffer db = new DoubleBuffer(theComponent);
    public void paint(Graphics g) {
       Graphics dbg = this.db.getBuffer();
       // ... add painting code performed on dbg ...
       this.db.paint(g);
    // Class
    import java.awt.*;
    * <code>DoubleBuffer</code> is a utility class for creating and managing
    * a double buffer for drawing on a component.  For a given component,
    * create a DoubleBuffer object, call getBuffer to get the graphics object
    * to draw on, then call paint with the component's graphics object to
    * draw the buffer. 
    * @author sampbe
    public class DoubleBuffer
        //~ Instance fields --------------------------------------------------------
         * The component.
        private Component comp = null;
         * The buffer width.
        private int bufferWidth = -1;
         * The buffer height.
        private int bufferHeight = -1;
         * The buffer image.
        private Image bufferImage = null;
         * The buffer graphics.
        private Graphics bufferGraphics = null;
        //~ Constructors -----------------------------------------------------------
         * Creates a new <code>DoubleBuffer</code> object for the specified
         * component.
         * @param comp the component
        public DoubleBuffer(Component comp)
            if(comp == null)
                throw new NullPointerException();
            this.comp = comp;
        //~ Methods ----------------------------------------------------------------
         * Paints the buffer on the graphics object.
         * @param g the graphics object to paint on
        public void paint(Graphics g)
            paint(g, 0, 0);
         * Paints the buffer on the graphics object.
         * @param g the graphics object to paint on
         * @param x the x-coordinate
         * @param y the y-coordinate
        public void paint(Graphics g, int x, int y)
            if(bufferImage != null)
                g.drawImage(bufferImage, 0, 0, comp);
         * Gets the width.
         * @return the width
        public int getWidth()
            return bufferWidth;
         * Gets the height.
         * @return the height
        public int getHeight()
            return bufferHeight;
         * Gets the buffer's graphics object.
         * @return the buffer's graphics
        public Graphics getBuffer()
            // checks the buffersize with the current panelsize
            // or initialises the image with the first paint
            if ((bufferWidth != comp.getSize().width)
                    || (bufferHeight != comp.getSize().height)
                    || (bufferImage == null)
                    || (bufferGraphics == null))
                // always keep track of the image size
                bufferWidth = comp.getSize().width;
                bufferHeight = comp.getSize().height;
                // clean up the previous image
                if (bufferGraphics != null)
                    bufferGraphics.dispose();
                    bufferGraphics = null;
                if (bufferImage != null)
                    bufferImage.flush();
                    bufferImage = null;
                // create the new image with the size of the panel
                bufferImage = comp.createImage(bufferWidth, bufferHeight);
                bufferGraphics = bufferImage.getGraphics();
            return bufferGraphics;
    }

  • Problem doing Applet exercise

    In my (swedish) course literature I am currently supposed to write an Applet that follows the actions of the window when it is resized . The point is to learn ComponentListener and making it runnable to avoid flickering.
    the applet is supposed to look like a red rectangle with a white cross.
    This is the script so far:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Main extends Applet implements ComponentListener{
        int left = 10, top = 10, rutbredd, ruth?jd;
        public void init(){
            Dimension appletsize = getSize();
            rutbredd = appletsize.width-20;
            ruth?jd = appletsize.height-20;
            addComponentListener( this);
        public void paint( Graphics g){
            Color col = new Color (255,0,0);
            g.setColor(col);
            g.fillRect(left,top,rutbredd,ruth?jd);
            g.setColor( Color.white);
            g.drawLine(left, top, left+rutbredd,top+rutbredd);
            g.drawLine(left+rutbredd,top,left, top+ruth?jd);
        public void componentResized( ComponentEvent e){
            Dimension appletsize =  getSize();
            if(rutbredd>appletsize.width-20){
                rutbredd=appletsize.width-20;
            if(rutbredd<appletsize.width-20){
                rutbredd=appletsize.width-20;
    }My mission is to make it runnable by adding 'Runnable' after 'implements ComponentListener' on the class-line and add these methods to the code:
        public void start(){
            Thread tr?d = new Thread( this);
            tr?d.start();
        public void run (){
            int fartbredd = -1, farth?jd = -1; // growth speed
            while(true){
                rutbredd += fartbredd;
                ruth?jd += farth?jd;
                Dimension appletSize= getSize();
                if(rutbredd <1){
                    fartbredd=1;
                if(rutbredd >appletSize.width){
                    fartbredd= -1;
                if(ruth?jd<1){
                    farth?jd=1;
                if(ruth?jd>appletSize.height){
                    farth?jd= -1;
                repaint();
                try { Thread.sleep(10);
                }catch( InterruptedException ie) {}
            }It does not say where to put these methods so I figured that perhaps I could put them just after the ones in script #1. Netbeans however gives an error message and Applet Viewer does not show any output at all.. (I get the usual 'Start: applet not intialized'). Does this work for anyone else?
    By the way, after copy-pasting it to another editor and back netbeans gives an error message on the first (originally working) script. This worked before I copied it to and back from another programming editor (bluefish). perhaps it is just netbeans not woking when moving stuff around too much?
    I have been trying to solve this for two hours. please help me put this script together!
    Thanks in advance.

    uj2n wrote:
    gives an error messageI'm sorry but I skipped the mind reading class at school. Perhaps you can share the error message(s) with us.

  • Anybody who wants to moderate an IO working program - come on do it

    It just works -- help to improvr
    run it first then try to understand
    The project is to be submitted before april 15th - I discovered java around August last year
    My programing background only Pascal - 4 years ago
    For a novice - I'm really good....in getting results... not in clean programming...sorry
    // legend
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ will mean a new file, another file or the end of the file
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ will mean read this instruction
    // ok lets go
    //^^^^^^^^^ The following code is written in notepad and saved as test.bat
    // this file can be saved in jdk/bin as test.bat
    //~~~~~~~~~ begin file > test.bat
    keytool -delete -alias mykey -keystore "C:\Program Files\JavaSoft\JRE\1.3.1\lib\security/cacerts" -storepass changeit
    javac newoscillo13.java
    jar cvf myoscillo.jar newoscillo13.class
    del c:\windows\.keystore
    keytool -genkey -alias mykey -keypass tarachand -dname "cn=test" -storepass tarachand
    jarsigner -signedjar hellosigned.jar -storepass tarachand myoscillo.jar mykey
    keytool -export -alias mykey -file mykey.cer -storepass tarachand
    keytool -import -file mykey.cer -keystore "C:\Program Files\JavaSoft\JRE\1.3.1\lib\security/cacerts" -storepass changeit
    del newoscillo13.class
    //~~~~~~~~~ end file > test.bat
    //^^^^^^^^^ save the following file as datafile.txt in jdk/bin
    //~~~~~~~~~ begin file > datafile.txt this file consists of data ranging from 0 to 300
    140 162 340 45 300 300 60 200 20 300
    100 16 2 45 300 3 50 64 250 220     
    100 360 20 390 40 50 25 10 0 294
    230 200 309 140 162 310 45 300 300 60 200 20
    //~~~~~~~~~ end file > more data must be added I've given u just this few
    //^^^^^ Heres the main program. save it as newoscillo13.java in jdk/bin
    //~~~~~~~~~~ begin newoscillo13.java
    import java.awt.*;
    import java.awt.Graphics;
    import java.applet.Applet;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.io.*;
    public class newoscillo13 extends Applet implements Runnable {
         Thread timer;// thread to produce a delay before repainting
         int delay = 1000;// delay between readings in ms
         boolean initialiser = true;
         String[] nowdate = new String[13];
    // defining the oscilloscope coordinates variables
         int screentop = 36;// where the oscillo grid starts
         int screenright = 55; // where the oscillo grid starts
         int screenheight = 400; // size of oscillo
         int screenwidth = 480;// size of oscillo
         int numofcolumns = 12;
         int numofrows = 10;
         int rowheight = screenheight/numofrows;
         int grid = screenwidth/(numofcolumns*5); // grid size
         int numofpoints = 61;
         int[] measuredval = new int[numofpoints +1]; // this array will contain the points to display on the oscillo
         int originx = screenright; // pixel coordinates 5
         int originy = (screentop+screenheight/2);// pixel coordinates 2 + 320/2 = 162
         int xmax = screenright + screenwidth;
         int ymax = screentop + screenheight;
         Color lineColor = Color.white;
         Color gridColor = Color.red;
         Color oscilloBgnd = Color.blue;
         Color fontColor = Color.black;
         Color borderColor = Color.red;
         Color measuredvaldispbgnd = Color.green;
    // start programing
         public void init() { }
    // starting paint
         public void paint(Graphics g){
         setBackground(Color.white);
         g.setColor(borderColor);
         g.fillRect(screenright-3,screentop-3,screenwidth+6,screenheight+6);
         g.setColor(oscilloBgnd);
         g.fillRect(screenright,screentop,screenwidth,screenheight);
         g.setColor(gridColor);
         g.drawLine(screenright,screentop+screenheight/2,screenright+screenwidth,screentop+screenheight/2);
         g.drawLine(screenright+screenwidth/2,screentop,screenright+screenwidth/2,screentop+screenheight);
         for (int i=screenright; i< screenright+screenwidth+1; i= i+grid*5) {
         g.drawLine(i,screentop,i,screentop+screenheight);}//vertical lines on oscillograph
         for (int i=screenright; i< screenright+screenwidth+1; i= i+grid) {
         g.drawLine(i,screentop+screenheight/2-5,i,screentop+screenheight/2+5);}
         for (int i=screentop; i< screentop+screenheight+1; i= i+screenheight/10) {
         g.drawLine(screenright,i,screenright+screenwidth,i);}// horizon lines on oscillograph
         for (int i=screentop; i< screentop+screenheight+1; i= i+screenheight/50) {
         g.drawLine(screenright+(screenwidth/2)-5,i,screenright+(screenwidth/2)+5,i);}
    // reading a text file > datafile.text placed in c:\jdk1.3.1\bin
    int [] measuredval = new int[numofpoints +1];     
    int measuredvalue;
    try {
    RandomAccessFile f = new RandomAccessFile ("c:\\jdk1.3.1\\bin\\datafile.txt", "r");
    int dataarraysize = 0;
    String s;
              while ( (s=f.readLine()) != null )                          {
                   StringTokenizer st = new StringTokenizer(s);
                                  while (st.hasMoreTokens()) {
                        measuredvalue = Integer.parseInt(st.nextToken());
                        if (dataarraysize < numofpoints +1) measuredval[dataarraysize] = measuredvalue;
                        if (dataarraysize>numofpoints) {
                        measuredval[numofpoints] = measuredvalue;
                        for (int k =1; k <= (numofpoints -1); k++) measuredval[k] = measuredval[k+1];
                        dataarraysize++;
                             }     // end while
                             }     // end try
    catch (Exception e) {System.out.println("Execption in constructor readertext13: "+e); } // end catch
                   for (int a = 0;a<=(numofpoints -1);a++){
                   if (measuredval[a] < 0) measuredval[a] = 0;
                   if (measuredval[a] > screenheight) measuredval[a] = screenheight;
                   //System.out.println(""+measuredval[a]);
    // display date and temperature horizontally below the oscilloscope
         SimpleDateFormat now1 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
         Date now = new Date();
         String nowstring = now1.format(now);
         g.setColor(measuredvaldispbgnd);
         g.fillRect(screenright - 4,ymax+5+40,screenwidth+8,20);
         int val = measuredval[numofpoints-1];
         g.setColor(fontColor);
         g.drawString(""+nowstring +" Temperature = "+val+"�C", screenright+10,ymax + 20+40);
    // x axis labelling - temporary
    SimpleDateFormat axisdate = new SimpleDateFormat("mm:ss");
    Date noww = new Date();
    while (initialiser) {
    for (int ii = 0; ii<13;ii++) nowdate[ii] = axisdate.format(noww);
    initialiser = false;}
    //---------------888888888888888
    // labelling x axis - time for each column
    for (int nw = 0;nw<12;nw++){
    nowdate[nw] = nowdate[nw + 1]; }
    nowdate[12] = axisdate.format(now);
    int wn = 0;
    while (wn <12) {
    g.drawString(nowdate[wn], screenright wn*40 - 17 ,screentopscreenheight+20);
    g.drawString(nowdate[wn+1], screenright +(wn+1)*40-17 ,screentop+screenheight+20);
    wn = wn +2;}
    g.drawString(nowdate[12], screenright + numofcolumns*40-17 ,screentop+screenheight+20);
    // label y axis
         //labeling vertical axis
         g.setColor(fontColor);
         for (int n = 0;n<11;n++) {
         int gridlabel = (screenheight - n*40);
         g.drawString(""+gridlabel+"�C", screenright - 45,screentop+screenheight*n/10 +4);
    // title label
         g.setColor(measuredvaldispbgnd);
         g.fillRect(screenright-3,5,screenwidth+5,20);
         g.setColor(fontColor);
         g.drawString("Graph of temperature measured against time at which it was measured", screenright+7, 18);
    // end label axes
         // draw another graphic , vertical display
         g.setColor(Color.gray);
         g.fillRect(xmax+10,screentop,16,screenheight+4 );
         g.setColor(gridColor);
         g.fillRect(xmax+12,screentop+2,12,screenheight);
         // above are fixed rectangles below is a pulsating rectangle depending on val
         g.setColor(oscilloBgnd);
         int zerotemp = screentop + screenheight + 2;
         int temperature = screenheight - val;
         g.fillRect(xmax+12,screentop+2,12,temperature);
    // end draw another graphic--------------------------------------------------------------
    // graphic display of temperature -- this is most important, the movie
         originx = screenright;
         originy = screentop + screenheight - measuredval[0];
    // draw 10 line segments     
         for (int i = 1; i <= (numofpoints -1);i++){
         g.setColor(lineColor);
         g.drawLine(originx,originy,originx+grid,screentop + screenheight - measuredval);
    // the starting point is originx, originy
    // the lowest point of the oscillograph is taken as 0, so screentop + screenheight
    // the end point of the line is originx+grid,screentop + screenheight - measuredval[i]
    // the above coordinates become the next starting point
         originx = originx+grid;
         originy = screentop + screenheight - measuredval[i];
    // ending paint
    public void destroy() {  }
    public void start() {
    timer = new Thread(this);
    timer.start();
    public void stop() {
    timer = null;
    public void run() {
    Thread me = Thread.currentThread();
    while (timer == me) {
    try {
    Thread.currentThread().sleep(delay);// wait for delay ms
    } catch (InterruptedException e) {
    System.out.println("Exception in method run: "+e);
    repaint();
    // start update to avoid flickering of the image
    private Image offScreenImage;
    private Dimension offScreenSize;
    private Graphics offScreenGraphics;
    public final synchronized void update (Graphics g) {
    Dimension d = getSize();
    if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height))
    offScreenImage = createImage(d.width, d.height);
    offScreenSize = d;
    offScreenGraphics = offScreenImage.getGraphics();
    offScreenGraphics.clearRect(0, 0, d.width, d.height);
    paint(offScreenGraphics);
    g.drawImage(offScreenImage, 0, 0, null); }
    // end update ton avoid flickering
    }// end applet
    //~~~~~~~~~~ end newoscillo13.java
    //^^^^^^^^^ now the html part
    //~~~~~~~~~ save as newoscillo13.html
    <HTML><BODY>
    <OBJECT classid="clsid:CAFEEFAC-0013-0001-0000-ABCDEFFEDCBA"
    codebase="http://java.sun.com/products/plugin/1.3.1/jinstall-131-win32.cab#Version=1,3,1,0" WIDTH=600 HEIGHT=600>
    <PARAM NAME = CODE VALUE = newoscillo13 >
    <PARAM NAME = ARCHIVE VALUE ="hellosigned.jar" >
    <PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.3.1">
    </OBJECT>
    </BODY></HTML>
    //~~~~~~~~~ save as newoscillo13.html in jdk/bin
    //^^^^^^^^^ go to dos > go to C:\jdk1.3.1\bin>
    //^^^^^^^^^ type test and then enter
    //^^^^^^^^^ wait to type yes and then enter
    // go back to windows, make sure java plug in advanced tab has c:\program files\javasoft\jre1.31
    now you can execute the html file newoscillo13.html and please it would be fantastic to
    send me your comments and suggestions to improve the program.
    I'm suzanne available at [email protected]

    Here are my suggestions:
    1) Get rid of the signing stuff -- you don't need it if you make the changes as I documented in the code posted below. Java applet can read any data file as long as the files are kept under the same document or code base -- notice that filename is specified without a path (i.e., it's relative). This makes it easier to deploy on the web
    2) Since you do not need to sign the applet, you don't need to create a jar file.
    3) Since you are not using anything special like swing, use the modified HTML shown below and you'll not have to worry about downloading Java plugin because the modified code will work with IE's native JVM version 1.1.4 and NN's native JVM version 1.1.5 -- should you make additions to the code, make sure that you're not calling methods implemented by Sun after the versions described.
    If this helps, give me the Dukes.... If you have more questions, ask!
    V.V.
    PS: The changes have been tested with the appletviewer, IE5, IE5.5, NN4.79 and NN6.2
    HTML
    ======
    <HTML><BODY>
    <APPLET CODE="newoscillo13.class" CODEBASE="." width=600 height=600></APPLET>
    </BODY></HTML>
    JAVA FILE
    ========
    import java.awt.*;
    import java.awt.Graphics;
    import java.applet.Applet;
    import java.util.*;
    import java.lang.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;        //<---------- V.V.
    public class newoscillo13 extends Applet implements Runnable {
       Thread timer;
       // thread to produce a delay before repainting
       int delay = 1000;
       // delay between readings in ms
       boolean initialiser = true;
       String[] nowdate = new String[13];
       // defining the oscilloscope coordinates variables
       int screentop = 36;
       // where the oscillo grid starts
       int screenright = 55;
       // where the oscillo grid starts
       int screenheight = 400;
       // size of oscillo
       int screenwidth = 480;
       // size of oscillo
       int numofcolumns = 12;
       int numofrows = 10;
       int rowheight = screenheight/numofrows;
       int grid = screenwidth/(numofcolumns*5);
       // grid size
       int numofpoints = 61;
       int[] measuredval = new int[numofpoints +1];
       // this array will contain the points to display on the oscillo
       int originx = screenright;
       // pixel coordinates 5
       int originy = (screentop+screenheight/2);
       // pixel coordinates 2 + 320/2 = 162
       int xmax = screenright +
          screenwidth;
       int ymax = screentop +
          screenheight;
       Color lineColor = Color.white;
       Color gridColor = Color.red;
       Color oscilloBgnd = Color.blue;
       Color fontColor = Color.black;
       Color borderColor = Color.red;
       Color measuredvaldispbgnd = Color.green;
       // start programing
       private URL Codebase;     //<---------- V.V.
       public void init() {
          Codebase=getCodeBase();     //<---------- V.V.
       // starting paint
       public void paint(Graphics g) {
          setBackground(Color.white);
          g.setColor(borderColor);
          g.fillRect(screenright-3,screentop-3,screenwidth+6,screenheight+6);
          g.setColor(oscilloBgnd);
          g.fillRect(screenright,screentop,screenwidth,screenheight);
          g.setColor(gridColor);
          g.drawLine(screenright,screentop+screenheight/2,screenright+screenwidth,screentop+screenheight/2);
          g.drawLine(screenright+screenwidth/2,screentop,screenright+screenwidth/2,screentop+screenheight);
          for (int i=screenright; i< screenright+screenwidth+1; i= i+grid*5) {
             g.drawLine(i,screentop,i,screentop+screenheight);
          //vertical lines on oscillograph
          for (int i=screenright; i< screenright+screenwidth+1; i= i+grid) {
             g.drawLine(i,screentop+screenheight/2-5,i,screentop+screenheight/2+5);
          for (int i=screentop; i< screentop+screenheight+1; i= i+screenheight/10) {
             g.drawLine(screenright,i,screenright+screenwidth,i);
          // horizon lines on oscillograph
          for (int i=screentop; i< screentop+screenheight+1; i= i+screenheight/50) {
             g.drawLine(screenright+(screenwidth/2)-5,i,screenright+(screenwidth/2)+5,i);
          // reading a text file > datafile.text placed in c:\jdk1.3.1\bin
          int [] measuredval = new int[numofpoints +1];
          int measuredvalue;
          try {
    //       RandomAccessFile f = new RandomAccessFile ("c:\\jdk1.3.1\\bin\\datafile.txt", "r");
    * Comments by V.V.
    * disk files are random but streams from network are not.  Since the data is being read sequentially anyway,
    * the modifications shown below will allow you to read the data file without the need for the applet to be signed
             URL url=new URL(Codebase,"datafile.txt");                       //<---------- put file in same directory as the class file ---- V.V.
             InputStream in;                                                 //<---------- V.V.
             URLConnection connection=url.openConnection();                  //<---------- V.V.
             in=connection.getInputStream();                                 //<---------- V.V.
             BufferedReader f=new BufferedReader(new InputStreamReader(in)); //<---------- V.V.
             int dataarraysize = 0;
             String s;
             while ((s=f.readLine()) != null ) {
                StringTokenizer st = new StringTokenizer(s);
                while (st.hasMoreTokens()) {
                   measuredvalue = Integer.parseInt(st.nextToken());
                   if (dataarraysize < numofpoints +1) measuredval[dataarraysize] = measuredvalue;
                   if (dataarraysize>numofpoints) {
                      measuredval[numofpoints] = measuredvalue;
                      for (int k =1; k <= (numofpoints -1); k++) measuredval[k] = measuredval[k+1];
                   dataarraysize++;
             // end while
          // end try
          catch (Exception e) {
             System.out.println("Execption in constructor readertext13: "+e);
          // end catch
          for (int a = 0;a<=(numofpoints -1);a++){
             if (measuredval[a] < 0) measuredval[a] = 0;
             if (measuredval[a] > screenheight) measuredval[a] = screenheight;
             //System.out.println(""+measuredval[a]);
          // display date and temperature horizontally below the oscilloscope
          SimpleDateFormat now1 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
          Date now = new Date();
          String nowstring = now1.format(now);
          g.setColor(measuredvaldispbgnd);
          g.fillRect(screenright - 4,ymax+5+40,screenwidth+8,20);
          int val = measuredval[numofpoints-1];
          g.setColor(fontColor);
          g.drawString(""+nowstring +
             " Temperature = "+val+
             "�C", screenright+10,ymax +
             20+40);
          // x axis labelling - temporary
          SimpleDateFormat axisdate = new SimpleDateFormat("mm:ss");
          Date noww = new Date();
          while (initialiser) {
             for (int ii = 0; ii<13;ii++) nowdate[ii] = axisdate.format(noww);
             initialiser = false;
          //---------------888888888888888
          // labelling x axis - time for each column
          for (int nw = 0;nw<12;nw++){
             nowdate[nw] = nowdate[nw +
                1];
          nowdate[12] = axisdate.format(now);
          int wn = 0;
          while (wn <12) {
             g.drawString(nowdate[wn], screenright wn*40 - 17 ,screentopscreenheight+20);
             g.drawString(nowdate[wn+1], screenright +(wn+1)*40-17 ,screentop+screenheight+20);
             wn = wn +2;
          g.drawString(nowdate[12], screenright +
             numofcolumns*40-17 ,screentop+screenheight+20);
          // label y axis
          //labeling vertical axis
          g.setColor(fontColor);
          for (int n = 0;n<11;n++) {
             int gridlabel = (screenheight - n*40);
             g.drawString(""+gridlabel+
                "�C", screenright - 45,screentop+screenheight*n/10 +4);
          // title label
          g.setColor(measuredvaldispbgnd);
          g.fillRect(screenright-3,5,screenwidth+5,20);
          g.setColor(fontColor);
          g.drawString("Graph of temperature measured against time at which it was measured", screenright+7, 18);
          // end label axes
          // draw another graphic , vertical display
          g.setColor(Color.gray);
          g.fillRect(xmax+10,screentop,16,screenheight+4 );
          g.setColor(gridColor);
          g.fillRect(xmax+12,screentop+2,12,screenheight);
          // above are fixed rectangles below is a pulsating rectangle depending on val
          g.setColor(oscilloBgnd);
          int zerotemp = screentop +
             screenheight +
             2;
          int temperature = screenheight - val;
          g.fillRect(xmax+12,screentop+2,12,temperature);
          // end draw another graphic--------------------------------------------------------------
          // graphic display of temperature -- this is most important, the movie
          originx = screenright;
          originy = screentop +
             screenheight - measuredval[0];
          // draw 10 line segments
          for (int i = 1; i <= (numofpoints -1);i++){
             g.setColor(lineColor);
             g.drawLine(originx,originy,originx+grid,screentop +
                screenheight - measuredval[ i ]);
             // the starting point is originx, originy
             // the lowest point of the oscillograph is taken as 0, so screentop + screenheight
             // the end point of the line is originx+grid,screentop + screenheight - measuredval
             // the above coordinates become the next starting point
             originx = originx+grid;
             originy = screentop +
                screenheight - measuredval[ i ];
          // ending paint
       public void destroy() {
       public void start() {
          timer = new Thread(this);
          timer.start();
       public void stop() {
          timer = null;
       public void run() {
          Thread me = Thread.currentThread();
          while (timer == me) {
             try {
                Thread.currentThread().sleep(delay);
                // wait for delay ms
             catch (InterruptedException e) {
                System.out.println("Exception in method run: "+e);
             repaint();
       // start update to avoid flickering of the image
       private Image offScreenImage;
       private Dimension offScreenSize;
       private Graphics offScreenGraphics;
       public final synchronized void update (Graphics g) {
          Dimension d = getSize();
          if ((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) {
             offScreenImage = createImage(d.width, d.height);
             offScreenSize = d;
             offScreenGraphics = offScreenImage.getGraphics();
          offScreenGraphics.clearRect(0, 0, d.width, d.height);
          paint(offScreenGraphics);
          g.drawImage(offScreenImage, 0, 0, null);
       // end update ton avoid flickering
    // end applett

  • Needed help with updating java code

    Hello all,
    Let me begin by let you know I am not a programmer and I have tried to solve this by reading on the net. I am a network admin so I tech knowledge but no programming.
    I have a webcam sending a Jpg to an FTP site and there I have used an applet called view.class to refresh once a second.
    site:http://70.154.170.253/webcamold.html
    My problems is now that it refreshes the same image over and over. It refreshes the cached image not the new image.
    From reading I suspect that it has to do with the newer version of java (it used to work fine).
    I have tried using JavaCam but same issue it just refreshes cached image. Also image flickers, the applet I am trying to fix was really smooth.
    I have also tried to compile code that I found on this forum but I got error dealing with deprecated code.
    Any help would be greatly appreciated!!!
    Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.io.PrintStream;
    public class View extends Applet
    implements Runnable
    public void init()
    setBackground(Color.white);
    String s = getParameter("refresh");
    if(s == null)
    update = 30;
    else
    try
    update = Integer.parseInt(s);
    catch(Exception _ex)
    update = 30;
    filename = getParameter("picture");
    if(filename == null)
    System.out.println("No filename given as parameter.");
    md = new MediaTracker(this);
    off = createImage(size().width, size().height);
    refreshImage();
    public void paint(Graphics g)
    g.drawImage(off, 0, 0, this);
    public void update(Graphics g)
    paint(g);
    public void refreshImage()
    img = getImage(getDocumentBase(), filename);
    md.addImage(img, 0);
    try
    md.waitForID(0);
    catch(Exception exception)
    exception.printStackTrace();
    Graphics g = off.getGraphics();
    g.drawImage(img, 0, 0, this);
    img.flush();
    public void run()
    while(th != null)
    try
    refreshImage();
    repaint();
    Thread.sleep(update * 1000);
    catch(Exception exception)
    System.out.println("Error when thread was supposed to sleep: " + exception.getMessage());
    public void start()
    if(th == null)
    th = new Thread(this);
    try
    th.start();
    return;
    catch(Exception exception)
    System.out.println("Couldn't start thread: " + exception.getMessage());
    return;
    } else
    return;
    public void stop()
    if(th != null)
    th.stop();
    th = null;
    public void destroy()
    stop();
    public View()
    update = 30;
    Thread th;
    String filename;
    int update;
    Image img;
    Image off;
    MediaTracker md;

    This is compile error free code and regarding your issues i don't think am good at this stuff
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    public class View extends Applet implements Runnable {
         Thread th;
         String filename;
         int update;
         Image img;
         Image off;
         MediaTracker md;
         public void init() {
              setBackground(Color.white);
              String s = getParameter("refresh");
              if (s == null) {
                   update = 30;
              } else {
                   try {
                        update = Integer.parseInt(s);
                   } catch (Exception _ex) {
                        update = 30;
              filename = getParameter("picture");
              if (filename == null) {
                   System.out.println("No filename given as parameter.");
              md = new MediaTracker(this);
              off = createImage(size().width, size().height);
              refreshImage();
         public void paint(Graphics g) {
              g.drawImage(off, 0, 0, this);
         public void update(Graphics g) {
              paint(g);
         public void refreshImage() {
              img = getImage(getDocumentBase(), filename);
              md.addImage(img, 0);
              try {
                   md.waitForID(0);
              } catch (Exception exception) {
                   exception.printStackTrace();
              Graphics g = off.getGraphics();
              g.drawImage(img, 0, 0, this);
              img.flush();
         public void run() {
              while (th != null) {
                   try {
                        refreshImage();
                        repaint();
                        Thread.sleep(update * 1000);
                   } catch (Exception exception) {
                        System.out.println("Error when thread was supposed to sleep: "
                                  + exception.getMessage());
         public void start() {
              if (th == null) {
                   th = new Thread(this);
                   try {
                        th.start();
                        return;
                   } catch (Exception exception) {
                        System.out.println("Couldn't start thread: "
                                  + exception.getMessage());
                   return;
              } else {
                   return;
         public void stop() {
              if (th != null) {
                   th.stop();
                   th = null;
         public void destroy() {
              stop();
         public View() {
              update = 30;
    }

  • Flickering problem with applet

    After doing a programming lab assignment, with no work, I decided to modify one of the completed programs, which was a pong-like game. Anyways, after changing it to a white on black setup, I now get major flickering. One of the previous programs was to animate something without it flickering using a buffered image. So I converted it over, but it had no effect.
    import java.applet.Applet;
    import java.awt.*;
    public class PongGame2 extends Applet
         int paddleX, paddleY, ballX, ballY, incX, incY, score, appletWidth, appletHeight;
         Image virtualMem;
         Graphics gBuffer;
         public void init()
              ballX = 10;
              ballY = 10;
              incX  = 3;
              incY  = 3;
              score = 0;
              appletWidth = getWidth();
              appletHeight = getHeight();
              virtualMem = createImage(appletWidth, appletHeight);
              gBuffer = virtualMem.getGraphics();
         public void paint(Graphics g)
              draw(g, paddleX, paddleY, ballX, ballY);
              ballX += incX;
              ballY += incY;
              if (incY > 0 && ballY > 580-incY)
                  incY = -incY;
              else if (incY < 0 && ballY < 2*incY)
                  incY = -incY;
              if (ballY < paddleY && ballY >= paddleY-20 && ballX > paddleX && ballX < paddleX+100)
                   incY = -incY;
              if (ballY > paddleY + 10 && ballY < paddleY + 20 && ballX > paddleX && ballX < paddleX+100)
                  incY = -incY;
              if (incX > 0 && ballX > 780-incX)
                  incX = -incX;
              else if (incX < 0 && ballX < 2*incX)
                  incX = -incX;
              if (ballY < 1)
                   score++;
               try
                    Thread.sleep(7);
               catch(InterruptedException ex)
              repaint();     
         public boolean mouseMove(Event e, int x, int y)
              paddleX = x-50;
              paddleY = y-10;          
              repaint();
              return true;
         public boolean mouseIdle(Event e, int x, int y)
              repaint();
              return true;
         public void createBackground(Graphics g)
              gBuffer.setColor(Color.black);
              gBuffer.fillRect(0,0,800,600);
              gBuffer.setColor(Color.white);   
              gBuffer.drawString("Score: " + score/5,200,20);
         public void draw(Graphics g, int paddleX, int paddleY, int ballX, int ballY)
              createBackground(g);
              gBuffer.setColor(Color.white);
              gBuffer.fillRect(paddleX,paddleY,100,20);
              gBuffer.fillOval(ballX,ballY,20,20);
              g.drawImage(virtualMem,0,0,this);
    }

    Petes1234, thanks!
    It works perfectly now, and without having warnings of using deprecated features. It took me a while though to find how to set this up, and proper methods.
    Here's the code right now:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    public class JavaPongGame1 extends JApplet implements MouseMotionListener
         int paddleX, paddleY, ballX, ballY, incX, incY, score;
         public void init()
              ballX = 10;
              ballY = 10;
              incX  = 3;
              incY  = 3;
              score = 0;
              addMouseMotionListener(this);
         public void paint(Graphics g)
              draw(g, paddleX, paddleY, ballX, ballY);
              ballX += incX;
              ballY += incY;
              if (incY > 0 && ballY > 580-incY)
                  incY = -incY;
              else if (incY < 0 && ballY < 2*incY)
                  incY = -incY;
              if (ballY < paddleY && ballY >= paddleY-20 && ballX > paddleX && ballX < paddleX+100)
                   incY = -incY;
              if (ballY > paddleY + 10 && ballY < paddleY + 20 && ballX > paddleX && ballX < paddleX+100)
                  incY = -incY;
              if (incX > 0 && ballX > 780-incX)
                  incX = -incX;
              else if (incX < 0 && ballX < 2*incX)
                  incX = -incX;
              if (ballY < 1)
                   score++;
              try
                    Thread.sleep(7);
               catch(InterruptedException ex)
              repaint();
         public void mouseMoved(MouseEvent e)
              paddleX = e.getX()-50;
              paddleY = e.getY()-10;          
              repaint();
              e.consume();
         public void mouseDragged(MouseEvent e)
         public void createBackground(Graphics g)
              g.setColor(Color.black);
              g.fillRect(0,0,800,600);
              g.setColor(Color.white);   
              g.drawString("Score: " + score/5,200,20);
         public void draw(Graphics g, int paddleX, int paddleY, int ballX, int ballY)
              createBackground(g);
              g.setColor(Color.white);
              g.fillRect(paddleX,paddleY,100,20);
              g.fillOval(ballX,ballY,20,20);
    }

  • Applet flickering

    I will award more Duke Dollars to the one/ones that give me an answer that will help solve my problem. Which is:
    I have an applet that displays some images. On IExplorer there is a visible flicker of one of the images (the largest one but i don't know if size has anything to do with it). The rest of the images do not flicker at all. On Netscape there is no such problem.
    The image is aquired from a gif file by clipping it, so doubble buffering is not the answer (at least as far as i know). I have tried drawing it with the drawImage() of java.awt.Graphics and i also tried to draw the image in a panel thus not having the drawImage() method called each time there is a repaint(). It did not help. The flickering seemed to be less frequent but it still is there and is very anoying. Again, that is only on IExplorer.
    Thank you,
    Calin

    As far as I know double buffering is used when drawing lots of stuff. When this happens the drawing can actually take some time so you would see a flicker on the screen as stuff is getting drawn. To make it all get on the screen at once, you use double buffering which means that you draw to an off-screen location, and then copy that to an on-screen location.
    As for my problem:
    1) i don't destroy the graphics context (or at least that's what i think); anyway, how can i destroy it ?? please give me an example and tell me how to avoid that
    2) Please give me an example of how to give it some sleep time, if it's something else then just calling sleep() on the current thread
    3) Most important, and no one addressed this: the problem i encounter is ONLY IN MS INTERNET EXPLORER
    Thank you,
    Calin

  • Flickering text print applet

    my news applet scrolls text across the screen, the text however is flickering. my draw code is below.
              screen2D.clearRect(0,0,getSize().width,getSize().height);
    screen2D.drawString(obj.news[obj.currentItem],obj.x,obj.y);
              repaint();
    your help would be much appreciated
    Arnold Oree

    Double Buffering would seem to be the answer to your problems. I'm no expert but the following worked for me where I previous was drawing directly to the screen. Do all your drawing in the offscreen buffer area and then transfer it to the screen with the last statement in your paint method.
    I've lifted some code for an applet I created a while back. Hopefully you can see what's going on.
    Override the update method
    as noted.
    // buffer stuff
    Graphics bufferGraphics;
    Image offScreen;
    Dimension dim;
    public void paint (Graphics g)
    bufferGraphics.clearRect(0,0,dim.width, dim.height);
    bufferGraphics.setFont(new Font ("serif", Font.BOLD,18));
    // set up board
    for (int row = 0; row <=7; ++ row)
    for (int column = 0; column <=7; ++ column)
    // white squares
    if ((row+column)%2 == 0)
    bufferGraphics.setColor (new Color(0,0,0));
    // black squares
    if ((row+column)%2 == 1)
    bufferGraphics.setColor (new Color (255,255,255));
    // attacked squares
    bufferGraphics.fillRect (40+(column*40), 75+(row*40), 40, 40);
    if (board [row][column] !=0)
    bufferGraphics.setColor (new Color(255,0,0));
    bufferGraphics.drawString("X", 52 +(column*40), 101 +(row*40));
    } // end row loop
    } // end column loop
    bufferGraphics.setColor (new Color (255,0,0));
    bufferGraphics.drawLine (38,73,360,73); // top
    bufferGraphics.drawLine (38,74,360,74); // top
    bufferGraphics.drawLine (38,75,360,75); // top
    bufferGraphics.drawLine (40,75,40,395); // left
    bufferGraphics.drawLine (39,75,39,395); // left
    bufferGraphics.drawLine (38,75,38,395); // left
    bufferGraphics.drawLine (38,395,360,395); // bottom
    bufferGraphics.drawLine (38,396,360,396); // bottom
    bufferGraphics.drawLine (38,397,360,397); // bottom
    bufferGraphics.drawLine (360,75,360,395); // right
    bufferGraphics.drawLine (361,73,361,397); // right
    bufferGraphics.drawLine (362,73,362,397); // right
    bufferGraphics.setColor (new Color (255,0,0));
    g.drawImage (offScreen, 0, 0, this);
    } // end paint
    public void update (Graphics g)
    paint (g);
    } // end update

  • Flickering in swing Applet

    I'm using swing applet.My applet is getting flickering only when i embed it in html
    I heard that,swing 'll handle flickering on its own.But i see it in appeltviewer it okie..My
    panel's size is also very big its,17040 pixel...what should i have to do avoid flickering

    My crystalball tells me that you are painting the entire screen with each call to paint and your are also making a call to super.paintComponent(g) when you do so... hence much flickering exists with your application even though it's double buffered.
    To avoid this problem do the following:
    take 3 whole slottered chickens, put them in a bag and ... oh that was for array problems... let me see for flickering....
    Well, you need to do offscreen rendering to an image and call repaint when done, but in your paintComponent(Graphics g) do this:
    public void paintComponent(Graphics g){
      drawImage(myOffscreenImage4Rendering, 0, 0, this); //notice 1 liner--no other code needed or wanted here.
    }I do this with 1600x1200 on an AMD 2GHz with 500+ objects being drawn and no flicker. I've had up to 10,000 objects with no flicker, but yes, the animation speed was severely impacted due to the number of objects being rendered each cycle.

  • Can anybody help in Flickering prob in Applet

    Hi there,
    I am having problem that my applet flickers a very often . actually i have a function which call repaint on mouse over. but i wanna reduce that. If anybody can help me in this matter would be greatful.
    thank u

    If you want to call repaint() method again and again, then you should redifine update method so that it should not paint the whole background. Better solution for this type of problem is to use getGraphics() method to get a Graphics object and paint any thing as you like with this Graphics object without needing paint or repaint method.

  • Applet flickers

    Hai,
    I developed an applet which works perfectly in appletviewer
    but flickers in IE browser. These problem arises when I dynamically
    set the components in various locations.
    regards,
    s.radhakrishnan

    call the setInvalidate() method before changing the postion or resizing of the components.

  • I need some help with my java game using applets, CAN SOMEBODY PLEASE HELP

    Hi,
    I am in the process of creating a RPG program using Java. I am not very experienced with java, however the problem i am currently facing is something i can't seem to figure out. I would like to draw a simple grid where a character (indicated by a filled circle) moves around this grid collecting items (indicated by a red rectangle). When the character moves on top of the grid with the item, i would like it to disappear. Right now i am not worrying about the fact that the item will reappear after the character moves away again, because sometimes, when the character moves over the item, nothing happens/another item disappears. i have been at this for 4 days and still cannot figure out what is goign on. can somebody please help me? it would be most appreciated.
    Thanks
    PS if i needed to send you my code, how do i do it?

    Thank you for replying.
    The thing is, I am taking java as a course, and it is necessary for me to start off this way (this is for my summative evaluation). i agree with you on the fact, however, that i should go in small steps. i have been doing that until this point, and my frustration caused me to jump around randomly for an answer. I also think that it may just be a bug, but i have no clue as to how to fix it, as i need to show my teacher at least a part of what i was doing by sometime next week. Here is my code for anybody willing to go through it:
    // The "Keys3" class.
    import java.applet.*;
    import java.awt.*;
    import java.awt.Event;
    import java.awt.Font;
    import java.awt.Color;
    import java.applet.AudioClip;
    public class Keys3 extends java.applet.Applet
        char currkey;
        int currx, curry, yint, xint;
        int itmval [] = new int [5],
            locval [] = new int [5],
            tempx [] = new int [5], tempy [] = new int [5],
            tot = 0, score = 0;
        boolean check = true;
        AudioClip bgSound, bgSound2;
        AudioClip hit;
        private Image offscreenImage;
        private Graphics offscreen;     //initializing variables for double buffering
        public void init ()  //DONE
            bgSound = getAudioClip (getCodeBase (), "sound2_works.au");
            hit = getAudioClip (getCodeBase (), "ah_works.au");
            if (bgSound != null)
                bgSound.loop ();
            currx = 162;
            curry = 68;
            setBackground (Color.white);
            for (int count = 0 ; count < 5 ; count++)
                itmval [count] = (int) (Math.random () * 5) + 1;
                locval [count] = (int) (Math.random () * 25) + 1;
            requestFocus ();
        public void paint (Graphics g)  //DONE
            resize (350, 270);
            drawgrid (g);
            if (check = true)
                pickitems (g);
                drawitems (g);
            g.setColor (Color.darkGray);
            g.fillOval (currx, curry, 25, 25);
            if (currkey != 0)
                g.setColor (Color.darkGray);
                g.fillOval (currx, curry, 25, 25);
            if (collcheck () != true)
                collision (g);
            else
                drawitems (g);
        } // paint method
        public void update (Graphics g)  //uses the double buffering method to overwrite the original
                                         //screen with another copy to reduce flickering
            if (offscreenImage == null)
                offscreenImage = createImage (this.getSize ().width, this.getSize ().height);
                offscreen = offscreenImage.getGraphics ();
            } //what to do if there is no offscreenImage copy of the original screen
            //draws the backgroudn colour of the offscreen
            offscreen.setColor (getBackground ());
            offscreen.fillRect (0, 0, this.getSize ().width, this.getSize ().height);
            //draws the foreground colour of the offscreen
            offscreen.setColor (getForeground ());
            paint (offscreen);
            //draws the offscreen image onto the main screen
            g.drawImage (offscreenImage, 0, 0, this);
        public boolean keyDown (Event evt, int key)  //DONE
            switch (key)
                case Event.DOWN:
                    curry += 46;
                    if (curry >= 252)
                        curry -= 46;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.UP:
                    curry -= 46;
                    if (curry <= 0)
                        curry += 46;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.LEFT:
                    currx -= 66;
                    if (currx <= 0)
                        currx += 66;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.RIGHT:
                    currx += 66;
                    if (currx >= 360)
                        currx -= 66;
                        if (hit != null)
                            hit.play ();
                    break;
                default:
                    currkey = (char) key;
            repaint ();
            return true;
        public boolean collcheck ()  //DONE
            if (((currx == tempx [0]) && (curry == tempy [0])) || ((currx == tempx [1]) && (curry == tempy [1])) || ((currx == tempx [2]) && (curry == tempy [2])) || ((currx == tempx [3]) && (curry == tempy [3])) || ((currx == tempx [4]) && (curry == tempy [4])))
                return false;
            else
                return true;
        public void collision (Graphics g)
            drawgrid (g);
            for (int count = 0 ; count < 5 ; count++)
                if ((currx == tempx [count]) && (curry == tempy [count]))
                    g.setColor (Color.darkGray);
                    g.fillOval (currx, curry, 25, 25);
                else if ((currx != tempx [count]) && (curry != tempy [count]))
                    g.setColor (Color.red);
                    g.fillRect (tempx [count], tempy [count], 25, 25);
        public void drawitems (Graphics g)
            for (int count = 0 ; count < 5 ; count++)
                g.setColor (Color.red);
                g.fillRect (tempx [count], tempy [count], 25, 25);
        public void pickitems (Graphics g)
            check = false;
            for (int count = 0 ; count < 5 ; count++)
                if (locval [count] <= 5)
                    tempy [count] = 22;
                else if (locval [count] <= 10)
                    tempy [count] = 68;
                else if (locval [count] <= 15)
                    tempy [count] = 114;
                else if (locval [count] <= 20)
                    tempy [count] = 160;
                else if (locval [count] <= 25)
                    tempy [count] = 206; //this determines the y-position of the item to be placed
                if (locval [count] % 5 == 0)
                    tempx [count] = 294;
                else if ((locval [count] == 1) || (locval [count] == 6) || (locval [count] == 11) || (locval [count] == 16) || (locval [count] == 21))
                    tempx [count] = 30;
                else if ((locval [count] == 2) || (locval [count] == 7) || (locval [count] == 12) || (locval [count] == 17) || (locval [count] == 22))
                    tempx [count] = 96;
                else if ((locval [count] == 3) || (locval [count] == 8) || (locval [count] == 13) || (locval [count] == 18) || (locval [count] == 23))
                    tempx [count] = 162;
                else if ((locval [count] == 4) || (locval [count] == 9) || (locval [count] == 14) || (locval [count] == 19) || (locval [count] == 24))
                    tempx [count] = 228;
        public void drawgrid (Graphics g)  //DONE
            g.drawRect (10, 10, 330, 230); //draws the outer rectangular border
            int wi = 10; //width of one square on the board
            int hi = 10; //height of one square on the board
            for (int height = 1 ; height <= 5 ; height++)
                for (int row = 1 ; row <= 5 ; row++)
                    if (((height % 2 == 1) && (row % 2 == 1)) || ((height % 2 == 0) && (row % 2 == 0)))
                        g.setColor (Color.gray);
                        g.fillRect (wi, hi, 66, 46);
                    else /*if (((height % 2 == 0) && (row % 2 == 1)) || ((height % 2 == 0) && (row % 2 == 0)))*/
                        g.setColor (Color.lightGray);
                        g.drawRect (wi, hi, 66, 46);
                        g.setColor (Color.lightGray);
                        g.drawRect (wi, hi, 66, 46); //drawn twice to make a shadow effect
                    wi += 66;
                wi = 10;
                hi += 46;
            } //this draws the basic outline of the game screen
    } // Keys3 class

  • How can i stop the screen from flickering in this program?

    Hi, i just wanted to know if anybody knows why my screen keeps flickering when i move.
    * @(#)CarWKeys.java
    * CarWKeys Applet application
    * @author
    * @version 1.00 2008/11/29
    import java.awt.*;
    import java.applet.*;
    import java.awt.image.*;
    public class CarWKeys extends Applet implements Runnable
          private Image dbImage;
         private Graphics dbg;
          Image img,CarWKeys1,cup;
          // This Field is to Trace out the User's CarWKeys position
          static int position=235;
          static int points = 0;
          // You can change this delay to any value which effects in the speed of the game
          static int delay = 100;
          road rd;
          Thread thr;
          static int pts=50;
          boolean msg=true;
          // If this field is true then the 'road' thread will be stopped
          static boolean kill=false;
          public void init()
         int x[] = { 15, 15, 0, 60, 45, 45 };
         int y[] = { 45, 50, 58, 58, 50, 45 };
         setBackground(Color.black);
                // Drawing the CarWKeys Image
                img = createImage(60,60);
                Graphics g = img.getGraphics();
                g.setColor(Color.black);
                g.fillRect(0,0,60,60);
                g.setColor(Color.green);
                g.fillRect(12,20,36,7);
                g.fillRect(8,15,4,17);
                g.fillRect(48,15,4,17);
                g.fillRect(5,40,50,7);
                g.fillRect(0,35,5,17);
                g.fillRect(55,35,5,17);
                g.setColor(Color.red);
                g.fillRect(20,0,20,15);
                g.fillRect(15,15,30,40);
                g.setColor(Color.blue);
                g.fillRect(20,20,7,10);
                g.fillRect(33,20,7,10);
                g.setColor(Color.red);
                g.fillRect(22,22,3,6);
                g.fillRect(35,22,3,6);
                g.setFont(new Font("TimesRoman",Font.PLAIN,7));
                g.setColor(Color.white);
                g.fillPolygon(x,y,6);
                g.setColor(Color.black);
                g.drawString("YAMAHA",15,52);
                // Drawing the CarWKeys Image
                CarWKeys1 = createImage(60,60);
                Graphics g1 = CarWKeys1.getGraphics();
                g1.setColor(Color.black);
                g1.fillRect(0,0,60,60);
                g1.setColor(Color.green);
                g1.fillRect(12,20,36,7);
                g1.fillRect(8,15,4,17);
                g1.fillRect(48,15,4,17);
                g1.fillRect(5,40,50,7);
                g1.fillRect(0,35,5,17);
                g1.fillRect(55,35,5,17);
                g1.setColor(Color.blue);
                g1.fillRect(20,0,20,15);
                g1.fillRect(15,15,30,40);
                g1.setColor(Color.red);
                g1.fillRect(20,20,7,10);
                g1.fillRect(33,20,7,10);
                g1.setColor(Color.blue);
                g1.fillRect(22,22,3,6);
                g1.fillRect(35,22,3,6);
                g1.setFont(new Font("TimesRoman",Font.PLAIN,7));
                g1.setColor(Color.white);
                g1.fillPolygon(x,y,6);
                g1.setColor(Color.black);
                g1.drawString(" B.M.W ",15,52);
                thr = new Thread(this); thr.start(); rd = new road(getGraphics(),CarWKeys1,this); rd.start();
                // Cup Image
                int a[] = {20,5,35};
                int b[] = {150,160,160};
                cup = createImage(50,165);
                Graphics handle = cup.getGraphics();
                handle.setColor(Color.black);
                handle.fillRect(0,0,50,165);
                handle.setColor(Color.red);
                handle.fillArc(0,40,40,30,0,180);
                handle.setColor(Color.yellow);
                handle.fillArc(0,15,40,80,180,180);
                handle.setColor(Color.red);
                handle.drawLine(20,95,20,150);
                handle.fillPolygon(a,b,3);
          public void update (Graphics g)
              // DoubleBuffers
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
          public void run()
                // If you cross the 50 mark you will get a Cup of Java
                while(points <= 15)
             if(points == 50 || kill == true)
             rd.stop();
             repaint();
             thr.stop();
             if((points%4)==0)
               rd.j = 0;
               pts = points;
                points++;
                            delay--;
                            if(delay <= 0)
                                  delay = 0;
                            rd.flag=1;
                            repaint();
                      try
                            Thread.sleep(delay);
                      }catch(InterruptedException exp){}
          public void destroy()
                thr.stop();
                rd.stop();
          //If User presses mouse the the CarWKeys is shifted to opposite side of the road
               public boolean keyDown(Event evt, int key) {
        if (key==Event.LEFT){
        // left arrow key pressed
        if(position == 355)
           position = 235;
        else if(key== Event.RIGHT){
        // right arrow key pressed
        if(position == 235)
           position = 355;
       repaint();
      return true;
          public void paint(Graphics gr)
                if(!kill)
                      if(msg)
                            // This is the opening message
                    gr.setColor(Color.black);
                    gr.fillRect(0,0,640,400);
                            gr.setColor(Color.yellow);
                            gr.setFont(new Font("TimesRoman",Font.BOLD,16));
                            gr.drawString("TO START THE GAME CLICK THE SCREEN",140,100);
                            gr.drawString("USE THE ARROW KEYS TO MOVE THE CAR",140,200);
                            gr.drawString("WAIT A MINUTE......",230,240);
                            msg = false;
                            try{
                                  Thread.sleep(3000);
                            }catch(Exception exp){}
                            gr.setColor(Color.black);
                            gr.fillRect(0,0,640,400);
                      gr.setColor(Color.white);
                      gr.fillRect(200,0,10,400);
                      gr.fillRect(440,0,10,400);
                      gr.drawImage(img,position,300,this);
                      gr.setColor(Color.yellow);
                      gr.fillRect(550,5,637,25);
                      gr.setColor(Color.blue);
                      gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                      gr.drawString("Score :"+pts,557,22);
                      if(points >= 16)
                            for(int xyz=0;xyz<3;xyz++)
                                  gr.setColor(Color.yellow);
                                  gr.drawString("Have a Cuppa Java",240,100);
                                  gr.drawImage(cup,300,100,this);
                                  gr.setColor(Color.yellow);
                                  gr.fillRect(550,5,637,25);
                                  gr.setColor(Color.blue);
                                  gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                                  gr.drawString("Score :50",557,22);
                                  try
                                        Thread.sleep(500);
                                  }catch(InterruptedException exp){}
                else
                      gr.setColor(Color.yellow);
                      gr.drawString("YOU HAVE LOST THE GAME",250,200);
    class road extends Thread
          int i;
          public static int j = 0;
          Graphics g;
          Image CarWKeys2;
          ImageObserver io;
          public static int flag = 0;
          boolean msg=true;
          road(Graphics g,Image CarWKeys2,ImageObserver io)
                this.g = g;
                this.io = io;
                this.CarWKeys2 = CarWKeys2;
          public void run()
                drawRoad(g);
          // The actual logic i.e Moving of CarWKeyss is here
          public void drawRoad(Graphics gr)
                if(msg)
                      gr.setColor(Color.black);
                      gr.fillRect(0,0,640,400);
                      gr.setColor(Color.yellow);
                      gr.setFont(new Font("TimesRoman",Font.BOLD,16));
                            gr.drawString("TO START THE GAME CLICK THE SCREEN",140,100);
                            gr.drawString("USE THE ARROW KEYS TO MOVE THE CAR",140,200);
                            gr.drawString("WAIT A MINUTE......",230,240);
                      msg = false;
                      try
                            Thread.sleep(3000);
                      }catch(Exception exp){}
                      gr.setColor(Color.black);
                      gr.fillRect(0,0,640,400);
                for(;j<=1000;j+=10)
                      for(i=-1000;i<=479;i+=60)
                            gr.setColor(Color.black);
                            gr.fillRect(320,i+j,10,i+j+50);
                            gr.setColor(Color.white);
                            gr.fillRect(320,i+j+10,10,i+j+60);
                      gr.clearRect(235,j-10,60,60);
                      gr.drawImage(CarWKeys2,235,0+j,io);
                      gr.clearRect(355,-150+(j-10),60,60);
                      gr.drawImage(CarWKeys2,355,-150+j,io);
                      gr.clearRect(235,-300+(j-10),60,60);
                      gr.drawImage(CarWKeys2,235,-300+j,io);
                      gr.clearRect(355,-450+(j-10),60,60);
                      gr.drawImage(CarWKeys2,355,-450+j,io);
                      if( (CarWKeys.position == 235 && (j >= 250 && j <= 360)) || (CarWKeys.position == 355 && (j >= 400 && j <= 510)) || (CarWKeys.position == 235 && (j >= 550 && j <= 660)) || (CarWKeys.position == 355 && (j >= 700 && j <= 810)) )
                            try
                                  Thread.sleep(2000);
                                  CarWKeys.kill = true;
                            }catch(InterruptedException exp){}
                      if (j >= 360 ) { if( (( j - 360 ) % 150 ) == 0 )
                            if(flag == 1)
                                  CarWKeys.points--;
                                  flag = 0;
                            CarWKeys.points++;
                            gr.setColor(Color.yellow);
                            gr.fillRect(550,5,637,25);
                            gr.setColor(Color.blue);
                            gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                            gr.drawString("Score :"+CarWKeys.points,557,22);
                try
                      Thread.sleep(CarWKeys.delay);
                }catch(InterruptedException exp){}
    }

    Look at the link I posted, you aren't double buffering correctly.
    I saw the other post you mistakenly made before you edited it. Not really a big deal, I was just wondering why you did that.

  • DoubleBuffering problem with applet

    Hi,
    We are developing an applet with multiple screens. CardLayout is being used to flip between different panels in the systems. The applet contains huge JTable and chart components and huge amount of data, which makes the refreshing of the applet very slow. We tried the DoubleBuffering concept to reduce the flickering in the JApplet class.
    Now the questions are:
    1) Do we need to do double buffering for all the panels that are used in the system ?
    2) Is there any other better way that Sun suggests to avoid flickering problems ?
    Any help will be much appreciated. Also with the email content and problem definition thread is going on, any feedback about this email is also welcomed.
    Thanks
    Anoop

    One solution is to put all the packages in a jar file.

  • Double buffering still gives flickering graphics.

    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    My questions are:
    Is the strategy used for double buffering correct?
    Why does it flicker?
    Why does the program change the priority a couple of times?
    Can you make fast games in JApplets or is there a better way to make games? (I think C++ is too hard)
    Here is the code:
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
    private Image dbImage;
    private Graphics dbg;
    private int radius = 20;
    private int xPos = 10;
    private int yPos = 100;
    * Initialization method that will be called after the applet is loaded
    * into the browser.
    @Override
    public void init() {
    //System.out.println(this.isDoubleBuffered()); //returns false
    // Isn't there a builtin way to force double buffering?
    // TODO start asynchronous download of heavy resources
    @Override
    public void start() {
    Thread th = new Thread(this);
    th.start();
    public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    while (true) {
    xPos++;
    repaint();
    try {
    Thread.sleep(20);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    @Override
    public void paint(Graphics g) {
    super.paint(g);
    //g.clear();//, yPos, WIDTH, WIDTH)
    g.setColor(Color.red);
    g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
    @Override
    public void update(Graphics g) {
    super.update(g);
    // initialize buffer
    if (dbImage == null) {
    dbImage = createImage(this.getSize().width, this.getSize().height);
    dbg = dbImage.getGraphics();
    // clear screen in background
    dbg.setColor(getBackground());
    dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
    // draw elements in background
    dbg.setColor(getForeground());
    paint(dbg);
    // draw image on the screen
    g.drawImage(dbImage, 0, 0, this);
    // TODO overwrite start(), stop() and destroy() methods
    }

    Somelauw wrote:
    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans.. AppletViewer is part of the JDK, not NetBeans.
    ..to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    Did you specifically mean the code mentioned on this page?
    [http://www.javacooperation.gmxhome.de/BildschirmflackernEng.html]
    Don't expect people to go hunting around the site, looking for the code you happen to be referring to.
    As an aside, please use the code tags when posting code, code snippets, XML/HTML or input/output. The code tags help retain the formatting and indentation of the sample. To use the code tags, select the sample and click the CODE button.
    Here is the code you posted, as it appears in code tags.
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
        private Image dbImage;
        private Graphics dbg;
        private int radius = 20;
        private int xPos = 10;
        private int yPos = 100;
         * Initialization method that will be called after the applet is loaded
         * into the browser.
        @Override
        public void init() {
            //System.out.println(this.isDoubleBuffered()); //returns false
            // Isn't there a builtin way to force double buffering?
            // TODO start asynchronous download of heavy resources
        @Override
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                xPos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            //g.clear();//, yPos, WIDTH, WIDTH)
            g.setColor(Color.red);
            g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
        @Override
        public void update(Graphics g) {
            super.update(g);
            // initialize buffer
            if (dbImage == null) {
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            // clear screen in background
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            // draw elements in background
            dbg.setColor(getForeground());
            paint(dbg);
            // draw image on the screen
            g.drawImage(dbImage, 0, 0, this);
        // TODO overwrite start(), stop() and destroy() methods
    }Edit 1:
    - For animation code, it would be typical to use a javax.swing.Timer for triggering updates, rather than implementing Runnable (etc.)
    - Attempting to set the thread priority will throw a SecurityException, though oddly it occurs when attempting to set the Thread priority to maximum, whereas the earlier call to set the Thread priority to minimum passed without comment (exception).
    - The paint() method of that applet is not double buffered.
    - It is generally advisable to override paintComponent(Graphics) in a JPanel that is added to the top-level applet (or JFrame, or JWindow, or JDialog..) rather than the paint(Graphics) method of the top-level container itself.
    Edited by: AndrewThompson64 on Jan 22, 2010 12:47 PM

Maybe you are looking for

  • Mfp 175

    My LaserJet 100 colorMFP M175nw is dropping off the network rather more often than I should have to put up with for a quality product. I can query the router and the printer is shown as being connected The IP adress in the config report is identical

  • WLC 5508 rebooted but still showing high uptime

    Hi all, I had to reboot our production WLC 5508 last night to apply a new adder license, which increased our AP count by 25. We run a DMZ mobility controller alongside the primary controller, which handles our mobile/guest WLANs using a Mobility Anch

  • Temporay tablespace grows rapidly. . .

    Dear All, When I run a large query the temporary tablespace grows continuously. The max size of temporary tablespace is 6G. I set Autoextend on, next size is 10m and maxsize is 6291456M. Also I set the SORT_AREA_SIZE = 256m. How to stop the rapid gro

  • Why do I get these errors?

    C:\jakarta-tomcat-4.1.29\webapps\projecttest\WEB-INF\classes\com\stardeveloper\web\listener\SessionCounter.java:6: package javax.servlet.http does not exist import javax.servlet.http.HttpSessionListener; ^ C:\jakarta-tomcat-4.1.29\webapps\projecttest

  • IMac 24" Core 2 Duo 2.16GHz Memory issue

    I just received a refurb iMac 24" Core 2 Duo 2.16GHz that came with a single 1GB memory module. I bought a 1GB module from Crucial. When both modules are installed, the computer doesn't chime and doesn't have any screen image nor does it boot. After