Stoping flicker in my applet.

Hi everyone. I currently am drawing a bunch of objects on an applet. I am going through an array of them, and I think the flicker is because each one is drawn separately. Is there any way to draw all of them at once to avoid this?
Here is my draw method.
     public void paint(Graphics g) {
          Graphics2D g2 = (Graphics2D) g; //Casting
          setBackground(Color.white);
          for(int j = 0; j < chessPieces.length; j++)
               chessPieces[j].getMeasure();
               chessPieces[j].draw(g2);
     }     // paint

Yes, draw them all onto a BufferedImage (in another method), and then just draw the completed BufferedImage onto the display area (from within paint). paint gets called alot ...like when the mouse passes over the display ...or when the browser gets resized/repositioned etc ...like, alot. When you set the background blank and redraw your stuff, you get the flickering that you are observing. If you draw it all onto an offscreen BufferedImage first (and only when the image NEEDS to change), then the whole previously created image gets drawn each time paint is called (repeatedly) and things look smooth. You might have to figure out BufferedImage a little, but the results are well worth it.

Similar Messages

  • Applet Screen Flicker with JRE 1.5.0_02 Onwards

    Hi, I have a problem with an Off-The-Shelf product which utilises a web-based Java Applet.
    When it was originally installed in the days of JRE 1.4.2 it worked fine but as the JRE's have been updated it has now taken on a screen flicker.
    After some lengthy investigations this seems to be as of JRE 1.5.0_02 (or JRE 5 Update 2), and after some reading I believed it was due to the update() of the repaint not including double-buffering, but as the problem does not exist before 1.5.0_02 I am bit confused.
    Obvioulsy rolling back the JRE for a lot of users is not a desired solution and as I do not have the source code I understand there may be no solution...
    Can anyone shed any light on this?
    Thanks in advance,
    Ashley

    Have you contacted the creators of the product, the ones with the source code? If it's popular enough, than many more will have experienced your problem and likely they have or are working on a solution.

  • Emergency! Help with flicker in applet!

    I have used the bufferstrategy technique before and I know all about double buffering and all, but I normaly ama programming with Frames and Canvas instead of Applets. My applet is flickering as I update the images on the screen can a bufferstrategy be used? Can anyone help me solve this flickering issue with applets?
    Thanks!
    (This is somewhat of an emergency so i will be giving out stars ^.^ )a

    Use JApplet not Applet, because JApplet is swing and is using JPanel as contentPane, and JPanel can be double-bufferised (true is default). You can also use the same buffer strategy.

  • Menu Flicker over applet when mouse move

    Hai!
    I have jsp file having menu and submenu. When I mouse over the menu item, if jsp file does not have any applet there is no problem.But if that jsp file has applet, menu is flickering. How to solve this problem?
    Thanks in advance
    Joe

    Is the menu over the applet area? I have a page like that, and I don't see a problem with flickering. The only problem I have (for which there is no solution) is that the dropdown menu part that goes into the applet area doesn't show (there's no way to force a DIV to draw on top of an applet).

  • Why when i scroll my Applet (in browser) it presents flicker?

    Hi everybody,
    as said in title when i use the scrollbar of Internet Explorer the whole thing flickers tremendously.
    I used Swing.Why does this happen?
    Thank you,
    Chris

    Do a search on double buffering maybe.
    /k1

  • How do I use a Frame to set up an applet animation?

    I am working on this program for a physics class. It is supposed to be an applet which animates a spring. I first set the animation with dummy values and it works fine (aside from a little flicker). I set up a frame which pops up and allows a user to input values. The frame looks and collects the information as I wanted; now I am trying to get these values passed to the init() method of my applet to be the basis of the animation. I was thinking something like JOptionPane; but, I wanted it to be more customized.
    This is the inner class in Launcher which prepares information and disposes the frame. I would like to pass this array
    "out."
         private class Exe implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   String execute = event.getActionCommand();
                   if (execute == "Ok"){
                        out = new double[5];
                        for(int c = 0; c < 5; c++){
                             out[c] = Double.parseDouble(input[c].getText());}
                        dispose();}}}}This is the init() method which sets up all the information required for the animation. I want to receive the array here:
    public class Spring extends Applet implements Runnable{
         double t = 0;
         double x,v,a,k;
         int s;
         int delay;
         Thread animator;
         double mass, omega, phi,gravity,equilibrium,amplitude, positionI, velocityI, phiHat;
         double scaler;
         Panel buttons;
         Button start;
         Button pause;
         Button back;
         Button forward;
         Button stop;
         Button restart;     
         Frame l;
         public void init(){
              //Opens the menu which allows user inputs
              l = new Launcher();
              l.setSize(500,450);
              l.setVisible(true);
              //Sets the ammount of time the system waits to refresh
              //Smaller numbers create a more accurate picture
              //This is in milliseconds
              delay = 100;
              //Calculates info about the system
              mass = 5;
              equilibrium = .5;
              gravity = 9.8;
              k = (mass * gravity)/equilibrium;
              omega = Math.pow(k/mass,.5);
              //Differential Equation
              positionI = .1;
              velocityI = -.1;
              amplitude = Math.pow(Math.pow((positionI/Math.cos(omega*0)),2)+
                        Math.pow((velocityI/(omega*Math.cos(omega*0))),2),.5);
              phiHat = Math.abs(Math.atan((positionI/Math.cos(omega*0))/(velocityI/(omega*Math.cos(omega*0)))));
              if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                   phi = phiHat;}
              if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                   phi = Math.PI + phiHat;}
              if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                   phi = (2*Math.PI) - phiHat;}
              if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                   phi = Math.PI - phiHat;}
              //scales the spring to the animation grid
              if (amplitude !=  0)
                   scaler = amplitude / 105;
              else
                   scaler = 1;
              //Adds buttons to applet          
              buttons = new Panel();
              buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
              start = new Button("Start");
              buttons.add(start);
              pause = new Button("Pause");
              buttons.add(pause);
              back = new Button("Back");
              buttons.add(back);
              forward = new Button("Forward");
              buttons.add(forward);
              stop = new Button("Stop");
              buttons.add(stop);
              restart = new Button("Restart");
              buttons.add(restart);
              this.setLayout(new BorderLayout());
              add(buttons, BorderLayout.SOUTH);}

    I was trying to tweak my animation and I have ran into some problems:
    To refresh, I have an applet which animates a spring. The equation which drives the animation is taken from user input which is entered in a frame that launches when the applet loads. The user has the option to control the animation with buttons as opposed to the applet running itself. Anyway, everything worked fine until I rewrote the applet with an image buffer. Now, the frame launches and is automatically placed in the background (on the desktop). The start, stop, and pause buttons work; but the step back and forward buttons do not work. If you have time to offer suggestions they would be appreciated.
    Set Up Buttons and Frame:
         public void init(){
              l = new Frame("Information About Your Spring");
              l.setLayout(new GridLayout(4,1));
              directions = new TextArea(text);
              directions.setEditable(false);
              l.add(directions);
              GravityHandler a = new GravityHandler();
              gravityButtons = new Container();
              gravityButtons.setLayout(new GridLayout(bodies.length/4,4));
              gravityL = new JRadioButton[bodies.length];
              g = new ButtonGroup();
              for(int x = 0; x < bodies.length; x++){
                   if(bodies[x].equals("Earth")){
                        gravityL[x] = new JRadioButton(bodies[x], true);
                        gravityL[x].addActionListener(a);}
                   else{
                        gravityL[x] = new JRadioButton(bodies[x], false);
                        gravityL[x].addActionListener(a);}
                   g.add(gravityL[x]);
                   gravityButtons.add(gravityL[x]);}
              l.add(gravityButtons);
              lables = new TextField[5];
              input = new TextField[5];
              otherInput = new Container();
              otherInput.setLayout(new GridLayout(3,4,5,5));
              lables[0] = new TextField("Mass:");
              lables[0].setEditable(false);
              otherInput.add(lables[0]);
              input[0] = new TextField(20);
              otherInput.add(input[0]);
              lables[1] = new TextField("Gravity:");
              lables[1].setEditable(false);
              otherInput.add(lables[1]);
              input[1] = new TextField("9.81",20);
              input[1].setEditable(false);
              otherInput.add(input[1]);
              lables[2] = new TextField("Equilibrium:");
              lables[2].setEditable(false);
              otherInput.add(lables[2]);
              input[2] = new TextField(20);
              otherInput.add(input[2]);
              lables[3] = new TextField("Displacement:");
              lables[3].setEditable(false);
              otherInput.add(lables[3]);
              input[3] = new TextField(20);
              otherInput.add(input[3]);
              lables[4] = new TextField("Initial Velocity:");
              lables[4].setEditable(false);
              otherInput.add(lables[4]);
              input[4] = new TextField(20);
              otherInput.add(input[4]);
              l.add(otherInput);
              Exe now = new Exe();
              buttonPlace = new Container();
              buttonPlace.setLayout(new FlowLayout(FlowLayout.CENTER));
              Ok = new Button("Ok");
              Ok.addActionListener(now);
              buttonPlace.add(Ok);
              l.add(buttonPlace);
              l.setSize(425,500);
              l.setResizable(false);
              l.toFront();
              l.setVisible(true);
              delay = 100;
              buttons = new Panel();
              buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
              start = new Button("Start");
              buttons.add(start);
              pause = new Button("Pause");
              buttons.add(pause);
              back = new Button("Back");
              buttons.add(back);
              forward = new Button("Forward");
              buttons.add(forward);
              stop = new Button("Stop");
              buttons.add(stop);
              restart = new Button("Restart");
              buttons.add(restart);
              this.setLayout(new BorderLayout());
              add(buttons, BorderLayout.SOUTH);
              display = createImage(size().width, size().height);
              dspl = display.getGraphics();
              l.toFront();}The frame is handled by ActionListener
    Action based on the buttons:
         public boolean action(Event e, Object args){
              if (e.target == start){
                   animator = new Thread(this);
                   animator.start();}
              if (e.target == stop){
                   animator.stop();
                   animator = null;
                   t = 0;
                   repaint();}
              if (e.target == pause){
                   animator.stop();
                   animator = null;}
              if (e.target == restart){
                   animator.stop();
                   animator = null;
                   t = 0;
                   repaint();
                   animator = new Thread(this);
                   animator.start();}
              if (e.target == back){
                   animator.stop();
                   animator = null;
                   t -= .1;
                   repaint();}
              if (e.target == forward){
                   animator.stop();
                   animator = null;
                   t += .1;
                   repaint();}
              return true;}
    draw animation:
         public void run(){
              while(Thread.currentThread() == animator){
                   try{
                        Thread.sleep(delay);}
                   catch(InterruptedException e){}
                   if(animator != null){
                        t+= .1;}
                   else{
                        repaint();}     
                   dspl.setColor(Color.black);
                   dspl.fillRect(0,0,size().width,size().height);
                   dspl.setColor(Color.white);
                   k = (mass * gravity)/equilibrium;
                   omega = Math.pow(k/mass,.5);
                   amplitude = Math.pow(Math.pow((positionI/Math.cos(omega*0)),2)+
                             Math.pow((velocityI/(omega*Math.cos(omega*0))),2),.5);
                   phiHat = Math.abs(Math.atan((positionI/Math.cos(omega*0))/(velocityI/(omega*Math.cos(omega*0)))));
                   if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                        phi = phiHat;}
                   if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                        phi = Math.PI + phiHat;}
                   if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                        phi = (2*Math.PI) - phiHat;}
                   if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                        phi = Math.PI - phiHat;}
                   if (amplitude !=  0)
                        scaler = amplitude / 105;
                   else
                        scaler = 1;
                   dspl.drawRect(5, 5, 442, 240);
                   dspl.drawLine(200,5,200,245);
                   dspl.drawLine(200,120,447,120);
                   dspl.drawLine(20,20, 20, 230);
                   dspl.drawLine(20, 20, 24, 20);
                   dspl.drawString( String.format("%.2f m", amplitude) , 24,21);
                   dspl.drawLine(20, 230, 24, 230);
                   dspl.drawString( String.format("%.2f m", amplitude) , 24,231);
                   dspl.drawLine(20, 125, 24, 125);
                   dspl.drawString( "0 m", 24, 126);
                   x = amplitude*Math.sin((omega*t)+phi); //Calculate position
                   v = (amplitude*omega)*Math.cos((omega*t)+phi); //Calculate velovity
                   a = -(Math.pow(omega,2)*amplitude)*Math.sin((omega*t)+phi); //Calculate acceleration
                   dspl.drawString("Kinematics:", 210,20);
                   dspl.drawString(String.format("Time: %.1f Seconds",t), 210, 40);
                   dspl.drawString(String.format("Position: %.2f m",x), 210,60 );
                   dspl.drawString(String.format("Velocity: %.2f m/s",v), 210,80 );
                   dspl.drawString(String.format("Acceleration: %.2f m/sec sq",a),210,100 );
                   dspl.drawString("Atributes:", 210, 140);
                   dspl.drawString(String.format("Equation: x(t) = %.2fsin(%.2ft + %.3f)",amplitude,omega,phi),210,160);
                   dspl.drawString(String.format("Spring Constant: %.2f n/m",k),210,180);
                   dspl.drawString(String.format("Period: %.2f Seconds", (2*Math.PI)/omega), 210,200);
                   dspl.drawString(String.format("Frequency: %.2f Hz",omega/(2*Math.PI)),210,220);
                   dspl.drawString(String.format("Amplitude: %.2f",amplitude),210,240);
                   s = (int) (x/scaler + 126);
                   dspl.drawLine(128,5,128,s-12);
                   dspl.drawString(String.format("%.0f kg Mass",mass), 104, s);
                   repaint();}}
         public void update(Graphics g){
              paint(g);}
         public void paint(Graphics g){
              g.drawImage(display,0,0,this);}Thanks

  • Embedding Applet in native Windows Application

    Hi!
    I need to integrate applet into my windows application (MSVC).
    The problem is displaying applet(s) within the application's main window (just like in browser).
    Is there a way to do it? Using WebBrowser (IE) ActiveX component is unacceptable.
    Perhaps there is documentation how to use JRE browser plugin, but googling yielded no results :(

    <offtopic>Apparently my login no longer working, re-registered</offtopic>
    ActiveX bridge won't do, I have to load an applet from any .jar
    The idea is to write kind of applet loader, which may be able to load jar and display applet.
    To start with, I need to know the way of paiting Java application GUI (i.e. JFrame) inside the native window.
    There is one way I've found. First, create borderless JFrame with some unique title, then use FindWindow in C++ Application to obtain HWND (window handle), and then call SetParent. I know there is more elegant way using JAWT to obtain HWND, the main problem is that Java window is rendered separately and only then becomes a part of native window, because HWND could be get on visible window only. This results unneccessary mess and flicking on screen for user.
    So, how can I render Java GUI directly to native window?
    I used search and haven't found solution.
    Thank you!
    PS found http://forum.java.sun.com/thread.jspa?forumID=52&threadID=5124062
    but this guy haven't said how he ded that :(
    Edited by: deniska25 on Oct 15, 2007 1:52 PM

  • Gnome applet Icons Missing

    I installed a fresh arch linux on another pc.  I installed gnome and gnome-extras. There is one problem:
    The icons on the "system tray" are missing. The applets are there but the icons are not shown:
    I already rebuilt the hicolor and gnome icons (and re-logged) with no result. Am I missing something?

    Ok here is something weird I found out.
    I am using xorg without xorg.conf. Since I have a Voodoo3 card I installed the xf86-video-tdfx driver. After a xorg restart the icons are working but the mouse flickers when I move it and there are graphic bugs when restoring windows.
    So I removed the tdfx driver and reverted to the vesa driver. The mouse does not flicker anymore but the applet icons are gone.

  • Duke Pt avail. 2nd time askin, (Flicker-free background) Simple Animation

    2nd time askin, since didn't get sufficient help. Duke Pts available! I am trying to create simple animation on a solid constant background. I used double buffering for moving the object and it works fine. But the problem is with the background image. The image seems to flicker while the object is moving. Here's my code:
    import java.awt.*;
    import java.applet.Applet;
    public class changed extends Applet implements Runnable{
    Image buffer;
    Graphics bufferg;
    Thread main;
    int x=0;
    boolean flag=false;
    public void init(){
    setSize(500,500);
    main=new Thread(this);
    main.start();
    buffer=createImage(getSize().width,getSize().height);
    bufferg=buffer.getGraphics();
    public void run(){
    while(main!=null){
    try     {
    main.sleep(50);
    catch(Exception e){}
    repaint();
    public void stop(){
    if(main!=null){main.stop();}
    public void paint(Graphics g){
    update(g);
    public void update(Graphics g){
    Dimension d=getSize();
    bufferg.setColor(getBackground());
    bufferg.fillRect(0,0,d.width,d.height);
    bufferg.setColor(Color.red);
    Image img = getImage(getCodeBase(),"bliss.jpg");
    if((x<500)&(!flag))
    bufferg.fillRect(x+=5,10,25,25);
    else
    flag=true;
    bufferg.fillRect(x-=5,10,25,25);
    if(x==0)
    flag=false;
    g.drawImage(img,50,50,this);
    g.drawImage(buffer,0,0,this);
    Please help me with this minor problem. I think what's happening is that the background is been drawn over and over again. I don't know how to make it constant and flicker-free.

    Possible 2 things:
    1. You're reloading the image on each repaint:
    Image img = getImage(getCodeBase(),"bliss.jpg");You shouldn't do that, you should just load it in init.
    2. You're drawing the image with the non-buffer Graphics "g" instead of "bufferg." You should use bufferg and draw it before anything else.
    I've modified the code for you, it should work but I can't test it because I don't have bliss.jpg. Let me know if it doesn't work.
    Here's the modified code:
    import java.awt.*;
    import java.applet.Applet;
    public class changed extends Applet implements Runnable {
         Image buffer,img;
         Graphics bufferg;
         Thread main;
         int x = 0;
         boolean flag = false;
         public void init() {
              setSize(500, 500);
              img = getImage(getCodeBase(), "bliss.jpg");
              main = new Thread(this);
              main.start();
              buffer = createImage(getSize().width, getSize().height);
              bufferg = buffer.getGraphics();
         public void run() {
              while (main != null) {
                   try {
                        main.sleep(50);
                   } catch (Exception e) {}
                   repaint();
         public void stop() {
              if (main != null) {
                   main.stop();
         public void paint(Graphics g) {
              update(g);
         public void update(Graphics g) {
              Dimension d = getSize();
              bufferg.drawImage(img, 50, 50, this);
              bufferg.setColor(getBackground());
              bufferg.fillRect(0, 0, d.width, d.height);
              bufferg.setColor(Color.red);
              if ((x < 500) & (!flag)) {
                   bufferg.fillRect(x += 5, 10, 25, 25);
              } else {
                   flag = true;
                   bufferg.fillRect(x -= 5, 10, 25, 25);
                   if (x == 0)
                        flag = false;
              g.drawImage(buffer, 0, 0, this);
    }

  • 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

  • Applet runs in Netscape Navigator

    I have a applet, when I run it on PC using IE, it is fine. but when I run it on Solaris using Navigator, it just can not be loaded.
    Someone please tell me the reason. Thank you very much!
    Sean

    It used to be that there was a different version of Java for each browser. This started because Java didn't have all the advaced features it does now and so different browsers would add new stuff to the language differently. Resently Sun Microsystems re-created Java and started forcing the Java enabled browsers to use their JRE. But IE stoped supporting Java, and only Netscape 6.0 or higher support Sun's JRE. This presents a problem for surffers because there are now 3 big different versions of Java that can be used, 2 of them are fading into the past though, but slowly.

  • Is it possible to rewrite  any applet to aplications ?

    I am wondering, is it possible to rewrite any applet to aplications ?
    dows everything works ? then ?
    look at this applet and please rewrite it to aplication if it works, I have tried but some sound did not work. and lots of other thigs went wrong.
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    public class PongBall
         // Variablen
         private int x_pos;               // x - Position des Balles
         private int y_pos;               // y - Position des Balles
         private int x_speed;          // Geschwindigkeit in x - Richtung
         private int y_speed;          // Geschwindigkeit in y - Richtung
         // Positionen
         private int ball_top;          // Obergrenze des Balles
         private int ball_bottom;     // Untergrenze des Balles
         private int ball_left;          // Linke Grenze des Balles
         private int ball_right;          // Rechte Grenze des Balles
         private int comp_top;          // Oberkante des Computerpaddels
         private int comp_bottom;     // Unterkante des Computerpaddels
         private int comp_right;          // Rechte Seite des Computerpaddels
         // Spielfeld (Radius des Balles mit eingerechnet)
         private static final int right_out = 390;
         private static final int left_out = 10;
         private static final int down_out =290;
         private static final int up_out = 10;
         private static final int radius = 10;               // Ballradius
         public PongBall (int x_pos, int y_pos)
              this.x_pos = x_pos;
              this.y_pos = y_pos;
              x_speed = 3;
              y_speed = 3;
         public void move ()
              x_pos += x_speed;
              y_pos += y_speed;
              isBallOut();
         public void isBallOut ()
              // Ball bewegt sich nach links
              if (x_speed < 0)
                   if (x_pos < left_out)
                        // Geschwindigkeit umdrehen
                        x_speed = - x_speed;
              // Ball bewegt sich nach rechts
              else if (x_speed > 0)
                   if (x_pos > right_out)
                        // Geschwindigkeit umdrehen
                        x_speed = - x_speed;
              // Ball bewegt sich nach oben
              if (y_speed < 0)
                   if (y_pos < up_out)
                        y_speed = - y_speed;
              // Ball bewegt sich nach unten
              else if (y_speed > 0)
                   if (y_pos > down_out)
                        y_speed = - y_speed;
         public void testForCollisionComputer (ComputerKI computer)
              // Initialisierung der Ballpositionen
              ball_top = y_pos - radius;
              ball_bottom = y_pos + radius;
              ball_left = x_pos - radius;
              ball_right = x_pos + radius;
              // Initialisierung der momentanen Positionen des Paddels
              comp_top = computer.getYPos();
              comp_bottom = computer.getYPos() + computer.getYSize();
              comp_right = computer.getXPos() + computer.getXSize();
              // Ist die Y - Position des Balles zwischen den Paddelpositionen?
              if ((ball_top >= comp_top - radius) && (ball_bottom <= comp_bottom + radius))
                   // Ist Paddel in der N�he?
                   if (ball_left <= comp_right)
                        // Normales Bouncen
                        x_speed = - x_speed;
         public int getXSpeed ()
              return x_speed;
         public int getYPos ()
              return y_pos;
         public void paint (Graphics g)
              g.setColor (Color.red);
              g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    import java.net.*;
    public class Main extends Applet implements Runnable
         // Variablen
         // Thread
         Thread thread;
         // Ball
         PongBall ball;
         // Computerpaddel
         ComputerKI computer;
         // Doppelpufferung
         private Image dbImage;
         private Graphics dbg;
         public void init(){
              setBackground (Color.black);
              ball = new PongBall (200,200);
              computer = new ComputerKI (200, ball);
         public void start(){
              thread = new Thread (this);
              thread.start();
         public void stop(){
              thread.stop();
         public void run(){
              // Erniedrigen der ThreadPriority um zeichnen zu erleichtern
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while (true)
                   // Neumalen des Fensters
                   repaint();
                   ball.move();
                   computer.move();
                   if (ball.getXSpeed() < 0){
                        ball.testForCollisionComputer(computer);
                   try
                        // Stoppen des Threads f�r 10 Millisekunden
                        Thread.sleep (10);
                   catch (InterruptedException ex)
                        break;
                   // Zur�cksetzen der ThreadPriority auf Maximalwert
                   Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void paint(Graphics g){
              ball.paint(g);
              computer.paint (g);
         /** Update - Methode, Realisierung der Doppelpufferung zur Reduzierung des Bildschirmflackerns */
         public void update (Graphics g)
              // Initialisierung des DoubleBuffers
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              // Bildschirm im Hintergrund l�schen
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              // Auf gel�schten Hintergrund Vordergrund zeichnen
              dbg.setColor (getForeground());
              paint (dbg);
              // Nun fertig gezeichnetes Bild Offscreen auf dem richtigen Bildschirm anzeigen
              g.drawImage (dbImage, 0, 0, this);
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    class ComputerKI
         /** Diese Klasse Implementiert die Bewegungen des Computers und zeichnet auch die
         Computerpaddel */
         // Deklaration der Variablen
         private int y_pos;                         // y - Position des Paddels
         private int y_speed;                    // Geschwindigkeit in y - Richtung
         private int real_y_pos;                    // Speichert die wirkliche Paddelposition (Mitte)
         // Konstanten
         private static final int x_pos = 15;     // x - Position des Paddels
         private static final int size_x = 10;     // Gr��e des Paddels in x - Richtung
         private static final int size_y = 50;     // Gr��e des Paddels in y - Richtung
         // Ball
         private static PongBall ball;
         // Construktor
         public ComputerKI (int y_pos, PongBall ball)
              this.y_pos = y_pos;
              y_speed = 4;
              this.ball = ball;
         /** Diese Methode bewegt das Paddel */
         public void move ()
              // Mitte des Paddels
              real_y_pos = y_pos + (size_y / 2);
              // Wenn sich Ball von Paddel wegbewegt, werden die Paddel in die Mitte zur�ckbewegt
              if (ball.getXSpeed() > 0)
                   // Paddel oberhalb der Mitte
                   if (real_y_pos < 148)
                        y_pos += y_speed;
                   // Paddel unterhalb der Mitte
                   else if (real_y_pos > 152)
                        y_pos -= y_speed;
              else if (ball.getXSpeed() < 0)
                   // Solange Paddel nicht auf H�he des Balles ist wird es bewegt
                   if ( real_y_pos != ball.getYPos())
                        // Ball oberhalb von Paddel
                        if (ball.getYPos() < real_y_pos)
                             y_pos -= y_speed;
                        // Ball unterhalb von Paddel
                        else if (ball.getYPos() > real_y_pos)
                             y_pos += y_speed;
         public int getXPos()
              return x_pos;
         public int getYPos()
              return y_pos;
         public int getXSize()
              return size_x;
         public int getYSize()
              return size_y;
         /** Diese Methode zeichnet das Paddel */
         public void paint (Graphics g)
              g.setColor (Color.blue);
              g.fillRect (x_pos, y_pos, size_x, size_y);
    }

    I tryed .. but couldent make it...
    there where not suck thing as MyStub and MyApplet..
    I know I sould replace it with something else.. but I
    did not know WHAT !!
    please help.
    MyStub stub = new MyStub();
    Applet a = new MyApplet();Ok this will be a bit longer post, but it contains fully functional example, simply copy-paste 200 lines of code to single .java file in your favourite IDE and explore it a bit.
    Please take note of that this is only example. It's design have several flaws:
    - user interface is tightly coupled wih applet stub/context. in real world application IMHO applet stub/context belong to application model (where 'application' means "MyAppletContainer") whereas JDesktop and JInternalFrame are part of view (from MVC pattern).
    - applet lifecycle is implmeneted very carelessly. in this example applet is initialzied and started uppon adding to JDesktop and stoped when JInternalFrame is removed from desktop
    - codeBase and documentBase properties of AppletStub are not set. see javadoc pages mentioned few lines below, for more information about this two properties.
    - some methods in applet context throws UnsupportedOperationException (e.g. getAudioClip) because they are beyond scope of simple example or not really necessary (e.g. mentioned getAudioClip). Another approach is return null instead or leave empty body for methods with void return type.
    Before studying sample code you should take a look on applet stub/context declaration in java api. visit url: http://java.sun.com/j2se/1.5.0/docs/api/java/applet/AppletStub.html and http://java.sun.com/j2se/1.5.0/docs/api/java/applet/AppletContext.html
    Because this sample is nothing else than briefly scratched one possible implementation of these two interfaces.
    Sample:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Main {
        public static void main(String[] args) throws Exception {
            final MyContext context = new MyContext();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    context.setVisible(true);
        /** Create sample applet */
        public static Applet createApplet() {
            JApplet applet = new JApplet() {
                public void init() {
                    showStatus("Another applet initialized");
            applet.add(new JLabel("I am applet"));
            return applet;               
    /** Single applet stub */
    class MyStub extends JInternalFrame implements AppletStub {       
        /** Create new applet stub*/
        public MyStub(Applet applet, MyContext context) {
            // Setup applet
            this.applet = applet;
            this.context = context;
            applet.setStub(this);
            add(applet);
        /** Owned applet */
        Applet applet;
        /** Context who own this stub */
        MyContext context;
        /** Applet document base */
        URL documentBase;
        /** Applet code base */
        URL codeBase;   
        /** Applet parameters */
        final Map<String, String> param =
                new HashMap<String, String>();   
        /** ##AppletStub##
         * Applet is active whenever frame
         * is selected for example.
        public boolean isActive() {
            return ((JInternalFrame)this).isSelected();
        /** ##AppletStub## */
        public URL getDocumentBase() {
            return documentBase;
        /** ##AppletStub## */
        public URL getCodeBase() {
            return codeBase;
        /** ##AppletStub## */
        public AppletContext getAppletContext() {
            return context;
        /** ##AppletStub## */
        public void appletResize(int width, int height) {
            // allow resize as needed
            setSize(width,height);
        /**##AppletStub## */
        public String getParameter(String name) {
            return param.get(name);
    /** Main application frame and applet context */
    class MyContext extends JFrame implements AppletContext {
        /** Named InputStreams */
        private Map<String,InputStream> streams =
                new HashMap<String, InputStream>();
        /** All applet stubs */
        private Map<String, MyStub> applets =
                new HashMap<String, MyStub>();
        /** Applets as enumeration */
        private Vector<Applet> appletsEnum =
                new Vector<Applet>();
        /** Ui applet container */
        private JDesktopPane jAppletPane =
                new JDesktopPane();
        /** Status line */
        private JLabel jAppletStatus =
                new JLabel("Add first applet");
        /** Create context */
        public MyContext() throws PropertyVetoException {
            // Create ui
            setSize(600,400);
            setDefaultCloseOperation(EXIT_ON_CLOSE);       
            setLayout(new BorderLayout());
            add(jAppletPane, BorderLayout.CENTER);
            add(jAppletStatus, BorderLayout.SOUTH);
            add(new JButton(new AbstractAction("Add applet") {
                public void actionPerformed(ActionEvent e) {
                    doAddApplet();
            }), BorderLayout.NORTH);
            // Very simple applet lifecycle implementation
            // Applet is initialized and started when added and
            // stopped and destroyed when removed from content pane
            jAppletPane.addContainerListener( new ContainerListener() {
                public void componentAdded(ContainerEvent e) {
                    Component c = e.getChild();
                    if (!(c instanceof MyStub))
                        return ;
                    Applet applet = ((MyStub)c).applet;
                    applet.init();
                    applet.start();
                public void componentRemoved(ContainerEvent e) {
                    Component c = e.getChild();
                    if (!(c instanceof MyStub))
                        return ;
                    Applet applet = ((MyStub)c).applet;
                    applet.stop();
                    applet.destroy();
        /** Add applet action body */
        private void doAddApplet() {
            // Create some arbitrary applet and name
            Applet applet = Main.createApplet();
            String appletName = "Applet "+System.currentTimeMillis();
            // Add applet and its stub to this container
            MyStub stub = new MyStub(applet, this);
            applets.put(appletName, stub);
            appletsEnum.add(applet);
            // Add to ui
            jAppletPane.add(stub);
            stub.setSize(400,300);
            stub.setVisible(true);
        /** ##AppletContext## */
        public Iterator<String> getStreamKeys() {
            return streams.keySet().iterator();
        /** ##AppletContext## */
        public void setStream(String key, InputStream stream)
        throws IOException {
            streams.put(key, stream);
        /** ##AppletContext## */
        public InputStream getStream(String key) {
            return streams.get(key);
        /** ##AppletContext## */
        public Enumeration<Applet> getApplets() {
            return appletsEnum.elements();
        /** ##AppletContext## */
        public Applet getApplet(String name) {
            MyStub stub = applets.get(name);       
            return stub == null? null: stub.applet;
        /** ##AppletContext## */
        public Image getImage(URL url) {
            try {
                return ImageIO.read(url);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this,
                        "IOException: "+ex.getMessage());
                return null;
        /** ##AppletContext## */
        public AudioClip getAudioClip(URL url) {
            throw new UnsupportedOperationException();
        /** ##AppletContext## */
        public void showStatus(String status) {
            jAppletStatus.setText(status);
        /** ##AppletContext## */
        public void showDocument(URL url, String target) {
            throw new UnsupportedOperationException();
        /** ##AppletContext## */
        public void showDocument(URL url) {
            showDocument(url, null);
    }Hope this will help a bit.
    ~~
    Adam
    Message was edited by:
    a3cchan
    When I've modified Main.createApplet() to create Your Pong applet I was able to create and run your applet in my simple container with just little glitches (mostly related to my simplistic implementation of ui).
    If you wish to 'convert' applet to swing application, You don't have use JDesktop. Add single applet to the frame instead. It should be quite simple from given example.

  • Applet blinks  when  launched  in a html page with black background

    Dear sirs:
    I 'm testing a game applet and preparing for deployment. However, whenever i reload the html page containg the applet, the applet will first appear as a white block and then switch to black-background( i set black as bg in first sentence at applet's init() ) .
    It's really annoying as the bgcolor of html is black. I try to set the applet and div's visibility be hidden, but the problems remains. And i try to add a black div covering on the applet( with z-index = 200) , it still blinks.
    Does anyone know how to startup the applet with background other than white?
    I use windows, and jre1.6.0.1 plugin.
    i Searched in google with no result.
    Thanks a lot.

    an initial fade in/out is added after init() function to reduce the flicking.
    some javascript tricks are used to reduce the white flashing after reloading. now it's much better and acceptable.
    However, i still want to know does anyone have some better tricks?
    There's a bug report in 2002 which is shown as "fixed", "closed". i think it's the same problem( in fact not fixed).
    The applet does not start up with the background color set in init() function. It first appears as a white block for 0.2-0.3 second, then switches to the user defined bgcolor . really annoying.

  • 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.

  • 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

Maybe you are looking for

  • Account Determination

    Hi friends I got the error while releasing the billing document to accounting, Posting keys for account determination for transaction EXD do not exist Message no. F5598 Diagnosis The posting keys necessary for account determination for transaction EX

  • Who do you categorize in Numbers 3.0

    The most useful feature of Numbers in iWorks 9 was the Categorize feature.  This alone made me switch over to Numbers from MS Excel.  However now Apple has removed this feature in Numbers 3.0!  How am I supposed to categorize with Numbers?  Do I retu

  • Cancel waiting call with SMS problem and advertisement

    Hi All, I've a serious problem and I appreciate if anyone can help me on it. Recently, I've upgraded my new Xperia Z1 to the latest software, but after I did that rejection calls with SMS is stop working and I don't know what to do for that !! Also,

  • ProjContext.Projects does not include master projects

    How do you get a list of all Projects, including master projects, from Project Online using the CSOM? I've tried the following code (copied from the docs), but it does not retrieve master projects: // List the published projects. private static void

  • Supplier not intended for purchasing organization message

    Hello All, We are implementing SAP SRM 7.03 with ECC 6.0. During SC creation stage we are getting a error message, 'Supplier not intended for purchasing organization' We are with one single purchasing organization, in the supplier search help the pur