Hot questions for Using Applets in paint

Question:

I have a question about overriding. I thought that overriding a method is re-writing that method. But, while I was studying about how to override, I got a doubt. Suppose that I have written following code:

import java.applet.Applet;

import java.awt.Graphics;

public class guitryings_2 extends Applet{

    public void paint( Graphics g )
    {
        g.drawString("Hi", 25, 75);
        showStatus("Deneme");
    }

}

If the paint method includes only g.drawString("Hi",25,75); and showStatus doesn't exist, I get a message 'Applet Started'.

If override means re-writing whole the method, when I write only g.drawStrings without, it means I didn't define any String that will be showed below. So shouldn't 'Applet Started' text disappear?


Answer:

Effectively, you are overriding java.awt.Container.paint(Graphics g) since neither Applet nor any class in the hierarchy up to Container provide their own implementation of paint().

This is the method you are overriding (and, yes, methods are always overridden as a whole - you can not override part of a method only. The only thing you can do is to call the overridden method, like super.paint(g)).

However, java.awt.Container.paint() does not contain any Applet specific code, hence the message which you see (Applet started) is obviously printed by the Applet container - like the browser (which still has the main control over its status bar), or the Applet Viewer.

On a side remark, note that Applets are being deprecated and some browsers already decommissioned the required native APIs to support Applets at all.

Question:

This is a noob question. We are being taught applets in class, and I was trying something on my own.

The following is the code

import java.awt.*;
import javax.swing.*;


class controls extends JPanel{

@Override public void paintComponent(Graphics g) {
    g.drawOval(50, 50, 50, 50); // <-- draws an oval on the panel
}

}

 public class test extends JApplet{
public void init(){
    final JPanel stage = new JPanel();
    final JPanel controlPanel = new controls();
    final JPanel banner = new JPanel();
    final JLabel name = new JLabel("Test", JLabel.CENTER);
    this.setLayout(new BorderLayout());
    banner.setBackground(Color.CYAN);
    banner.add(name);
    this.add(controlPanel, BorderLayout.WEST);
    this.add(banner, BorderLayout.NORTH);
}
}

As far as I understand, paintComponent() need not be called explicitly. The controls class works well when used alone.

I mean the following code works.

public class test extends JApplet{
public void init(){
    JPanel controlPanel = new controls();
    this.add(controlPanel);
}
}

I am not able to understand the difference. Why does the same code work in this case, and not in the previous?

Thank you.


Answer:

Override public Dimension getPreferredSize() (and return a new Dimension) in the controls class. When putting components in WEST the width will be determined by the preferredSize. If you don't override getPreferredSize, the preferred size will be 0. The CENTER will take up the rest of the space, after the WEST, ect is calculated. The second case works because it is in the CENTER of the default BorderLayout

Question:

I've been trying to print using the drawString() function of Graphics class in a method other than paint(). I've tried this program which was the solution to an earlier doubt, but this code is not working. Please find me the flaws. Thanks. Here's it below:

import java.awt.*;
import java.applet.*;

public class PaintIssue extends Applet {

    Graphics gg; //global Graphics object

    @Override
    public void init() {}

    @Override
    public void paint(Graphics g) {
        g.drawString("Output of paint method",20,20);
        myMethod(); //calling myMethod
    }

    public static void myMethod() {
        gg.drawString("Output of myMethod",20,40);
    }
}

Answer:

AWT doesn't have a concept of a "global graphics object". You have to pass down the Graphics object that your paint method receives.

    @Override
    public void paint(Graphics g) {
        g.drawString("Output of paint method",20,20);
        myMethod(g); //calling myMethod
    }

    public static void myMethod(Graphics g) {
        g.drawString("Output of myMethod",20,40);
    }

Question:

This is a java Applet game. There are 3 game states, Running, Dead and Win. My question is two part, but I think they are related since they happen at the same point.

Question 1: When you die by losing all your health the "Start over" button is displayed once. When you die by falling in a hole, it fills the screen over and over. It also fills the screen when you "win" the level.

Question 2: Same criteria as question 1, only this time about sound. Death by enemy plays the "death" song. Death by hole causes the song to glitch over and over on the first note, as though it is caught in a loop. Winning makes the win song glitch the same way.

package androidGame;

import java.applet.Applet;
import java.awt.event.*;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.net.*;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import androidGame.framework.Animation;

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener,
        ActionListener {

    enum GameState {
        Running, Dead, Win
    }

    GameState state = GameState.Running;

    private static Robot robot;
    public static Heliboy hb, hb2, hb3, hb4, hb5, hb6, hb7, hb8, hb9, hb10,
            hb11, hb12, hb13, hb14, hb15, hb16;
    public static int score = 0;
    public static int rHealth = 120;
    private Font font = new Font(null, Font.BOLD, 30);

    private Image image, currentSprite, character, character2, character3,
            characterDown, characterJumped, background, heliboy, heliboy2,
            heliboy3, heliboy4, heliboy5;

    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
            tilegrassRight, tiledirt, tilefire, tiledoor;

    private Graphics second;
    private URL base;
    private static Background bg1, bg2;
    private Animation anim, hanim;
    int level = 1;
    Button next, sOver;

    private ArrayList<Tile> tilearray = new ArrayList<Tile>();

    @Override
    public void init() {

        setSize(800, 480);
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Robot Mania");
        try {
            base = getDocumentBase();
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Image Setups
        character = getImage(base, "data/character.png");
        character2 = getImage(base, "data/character2.png");
        character3 = getImage(base, "data/character3.png");

        characterDown = getImage(base, "data/down.png");
        characterJumped = getImage(base, "data/jumped.png");

        heliboy = getImage(base, "data/heliboy.png");
        heliboy2 = getImage(base, "data/heliboy2.png");
        heliboy3 = getImage(base, "data/heliboy3.png");
        heliboy4 = getImage(base, "data/heliboy4.png");
        heliboy5 = getImage(base, "data/heliboy5.png");

        background = getImage(base, "data/trees.png");

        tiledirt = getImage(base, "data/tiledirt.png");
        tilegrassTop = getImage(base, "data/tilegrasstop.png");
        tilegrassBot = getImage(base, "data/tilegrassbot.png");
        tilegrassLeft = getImage(base, "data/tilegrassleft.png");
        tilegrassRight = getImage(base, "data/tilegrassright.png");
        tilefire = getImage(base, "data/tilefire.png");
        tiledoor = getImage(base, "data/tiledoor.png");

        anim = new Animation();
        anim.addFrame(character, 1250);
        anim.addFrame(character2, 50);
        anim.addFrame(character3, 50);
        anim.addFrame(character2, 50);

        hanim = new Animation();
        hanim.addFrame(heliboy, 100);
        hanim.addFrame(heliboy2, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy5, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy2, 100);

        currentSprite = anim.getImage();
    }

    @Override
    public void start() {
        // Sound.MAIN.loop();
        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        robot = new Robot();
        // Initialize Tiles
        try {
            loadMap("data/map" + level + ".txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Random random = new Random();
        int randomInt = random.nextInt(500);

        hb = new Heliboy(700, 360);
        hb2 = new Heliboy(900 + randomInt, 360);
        hb3 = new Heliboy(2300 + randomInt, 360);
        hb4 = new Heliboy(2900 + randomInt, 360);
        hb5 = new Heliboy(3400 + randomInt, 360);
        hb6 = new Heliboy(3900 + randomInt, 360);
        hb7 = new Heliboy(4300 + randomInt, 360);
        hb8 = new Heliboy(4700 + randomInt, 360);
        hb9 = new Heliboy(5000 + randomInt, 360);
        hb10 = new Heliboy(5300 + randomInt, 360);
        hb11 = new Heliboy(5700 + randomInt, 360);
        hb12 = new Heliboy(6000 + randomInt, 360);
        hb13 = new Heliboy(6300 + randomInt, 360);
        hb14 = new Heliboy(6700 + randomInt, 360);
        hb15 = new Heliboy(7000 + randomInt, 360);
        hb16 = new Heliboy(7200 + randomInt, 360);

        Thread thread = new Thread(this);
        thread.start();
    }

    private void loadMap(String filename) throws IOException {
        ArrayList lines = new ArrayList();
        int width = 0;
        int height = 0;

        BufferedReader reader = new BufferedReader(new FileReader(filename));
        while (true) {
            String line = reader.readLine();
            // no more lines to read
            if (line == null) {
                reader.close();
                break;
            }

            if (!line.startsWith("!")) {
                lines.add(line);
                width = Math.max(width, line.length());

            }
        }
        height = lines.size();

        for (int j = 0; j < 12; j++) {
            String line = (String) lines.get(j);
            for (int i = 0; i < width; i++) {

                if (i < line.length()) {
                    char ch = line.charAt(i);
                    Tile t = new Tile(i, j, Character.getNumericValue(ch));
                    tilearray.add(t);
                }

            }
        }

    }

    @Override
    public void run() {
        if (state == GameState.Running) {

            while (true) {

                robot.update();
                if (robot.isJumped()) {
                    currentSprite = characterJumped;
                } else if (robot.isJumped() == false
                        && robot.isDucked() == false) {

                    currentSprite = anim.getImage();
                }

                ArrayList projectiles = robot.getProjectiles();
                for (int i = 0; i < projectiles.size(); i++) {
                    Projectile p = (Projectile) projectiles.get(i);
                    if (p.isVisible() == true) {
                        p.update();

                    } else {
                        projectiles.remove(i);
                    }
                }

                updateTiles();
                hb.update();
                hb2.update();
                hb3.update();
                hb4.update();
                hb5.update();
                hb6.update();
                hb7.update();
                hb8.update();
                hb9.update();
                hb10.update();
                hb11.update();
                hb12.update();
                hb13.update();
                hb14.update();
                hb15.update();
                hb16.update();
                bg1.update();
                bg2.update();
                animate();
                repaint();
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (rHealth == 0) {
                    state = GameState.Dead;
                    Sound.MAIN.stop();
                    // Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);
                    revalidate();
                    repaint();
                }
                if (robot.getCenterY() > 500) {
                    state = GameState.Dead;
                    Sound.MAIN.stop();
                    // Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);
                    revalidate();
                    repaint();

                }

                if (score == 35) {
                    state = GameState.Win;
                    Sound.MAIN.stop();
                    // Sound.WIN.play();

                    next = new Button("Next Level");
                    this.add(next);
                    next.addActionListener(this);
                    next.setVisible(true);
                    revalidate();
                    repaint();

                }
            }
        }
    }

    public void animate() {
        anim.update(10);
        hanim.update(50);
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            second = image.getGraphics();
        }

        second.setColor(getBackground());
        second.fillRect(0, 0, getWidth(), getHeight());
        second.setColor(getForeground());
        paint(second);

        g.drawImage(image, 0, 0, this);

    }

    @Override
    public void paint(Graphics g) {

        if (state == GameState.Running) {

            g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
            g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
            paintTiles(g);

            ArrayList projectiles = robot.getProjectiles();
            for (int i = 0; i < projectiles.size(); i++) {
                Projectile p = (Projectile) projectiles.get(i);
                g.setColor(Color.BLUE);
                g.fillRect(p.getX(), p.getY(), 10, 5);
            }

            g.drawImage(currentSprite, robot.getCenterX() - 61,
                    robot.getCenterY() - 63, this);
            g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
                    hb.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
                    hb2.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb3.getCenterX() - 48,
                    hb3.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb4.getCenterX() - 48,
                    hb4.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb5.getCenterX() - 48,
                    hb5.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb6.getCenterX() - 48,
                    hb6.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb7.getCenterX() - 48,
                    hb7.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb8.getCenterX() - 48,
                    hb8.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb9.getCenterX() - 48,
                    hb9.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb10.getCenterX() - 48,
                    hb10.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb11.getCenterX() - 48,
                    hb11.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb12.getCenterX() - 48,
                    hb12.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb13.getCenterX() - 48,
                    hb13.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb14.getCenterX() - 48,
                    hb14.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb15.getCenterX() - 48,
                    hb15.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb16.getCenterX() - 48,
                    hb16.getCenterY() - 48, this);

            g.setFont(font);
            g.setColor(Color.WHITE);
            g.drawString("Health: " + Integer.toString(rHealth), 5, 30);
            g.drawString("Score: " + Integer.toString(score), 650, 30);

        } else if (state == GameState.Dead) {
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You're Dead!", 300, 200);
            g.drawString("Score: " + score, 300, 250);

        } else if (state == GameState.Win) {
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You Beat this level!", 300, 200);
            g.drawString("Score: " + score, 300, 250);
        }
    }

    private void updateTiles() {

        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            t.update();
        }

    }

    private void paintTiles(Graphics g) {
        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = characterDown;
            if (robot.isJumped() == false) {
                robot.setDucked(true);
                robot.setSpeedX(0);
            }
            break;

        case KeyEvent.VK_LEFT:
            robot.moveLeft();
            robot.setMovingLeft(true);
            break;

        case KeyEvent.VK_RIGHT:
            robot.moveRight();
            robot.setMovingRight(true);
            break;

        case KeyEvent.VK_SPACE:
            robot.jump();
            break;

        case KeyEvent.VK_CONTROL:
            if (robot.isDucked() == false && robot.isJumped() == false
                    && robot.isReadyToFire()) {
                robot.shoot();
                robot.setReadyToFire(false);

            }
            break;

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = anim.getImage();
            robot.setDucked(false);
            break;

        case KeyEvent.VK_LEFT:
            robot.stopLeft();
            break;

        case KeyEvent.VK_RIGHT:
            robot.stopRight();
            break;

        case KeyEvent.VK_SPACE:
            break;

        case KeyEvent.VK_CONTROL:
            robot.setReadyToFire(true);
            Sound.GUN.play();
            break;

        }

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public static Background getBg1() {
        return bg1;
    }

    public static Background getBg2() {
        return bg2;
    }

    public static Robot getRobot() {
        return robot;
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == next) {
            level++;
        }

        if (evt.getSource() == sOver) {
            level = 1;
        }
    }

}

Here is the Sound.java class that calls the sound files (Though I don't think it is needed for this particular question)

package androidGame;

import java.applet.Applet;
import java.applet.AudioClip;

public class Sound {
    public static final AudioClip MAIN = Applet.newAudioClip(Sound.class.getResource("soundtrack.au"));
    public static final AudioClip GUN = Applet.newAudioClip(Sound.class.getResource("gun.au"));
    public static final AudioClip DIE = Applet.newAudioClip(Sound.class.getResource("death.au"));
    public static final AudioClip WIN = Applet.newAudioClip(Sound.class.getResource("win.au"));
}

Answer:

The answer was that the game was getting stuck in a loop on "win" or on "death by falling in a hole". Although I acknowledge it is not the most elegant of solutions, changing the code reflected below solves the problem.

                if (rHealth == 0) {
                    state = GameState.Dead;
                    Sound.MAIN.stop();
                    Sound.DIE.play();
                }

                if (robot.getCenterY() > 500) {
                    state = GameState.Dead;
                    robot.setCenterY(0);
                    robot.setCenterX(0);
                    Sound.MAIN.stop();
                    Sound.DIE.play();
                }

                if (score == 35) {
                    state = GameState.Win;
                    score = 40;
                    Sound.MAIN.stop();
                    Sound.WIN.play();
                }
            } 

Question:

Whenever I drag to change the window size in my applet, the paint method appears to run again. What is really happening? Is the paint method just re-running itself? Is there a way I can make it do this automatically (without changing the window size)? The for loop does not seem to be working. I had a thread.sleep method in the code but it still didn't help. I will include the code for the paint method below.

// -----------------------------------------------------------------
// Paints the stick figures on the applet.
// -----------------------------------------------------------------
public void paint(Graphics page) {
    // for (int f = 0; f < 6; f++) {

    resize(400, 150);
    for (int u = 0; u < stickdudes.length; u++)
        stickdudes[u].draw(page);

    // Delay.sleep(3000);
    // }
}

Answer:

to call the paint() method again and again the repaint() method is used both in AWT and Swing

Question:

I have an applet that's only purpose is to create a box and each time it's painted it changes color. Right now it is not changing color at all, it simply creates a random background color to start and sticks with it whenever painted but I need it to change. Any help on what I'm doing wrong would be appreciated.

import java.applet.*;
import java.awt.*;
import java.util.*;

public class AppletSubClass2 extends Applet {
public void init() {
    System.err.println("Hello from AnAppletSubClass.init");
    setBackground(color);
}
public void paint(Graphics g) {
    System.err.println("Hello from .paint!This time the applet will change colors when painted");
    setBackground(new Color(randomNum1, randomNum2, randomNum3));
}
Random rand = new Random();
int randomNum1 = rand.nextInt(251);
int randomNum2 = rand.nextInt(251);
int randomNum3 = rand.nextInt(251);
Color color = new Color(randomNum1, randomNum2, randomNum3);
}

Answer:

You've basically broken the paint chain, nothing is actually painting your background color...

You could do something like...

public void paint(Graphics g) {
    int randomNum1 = rand.nextInt(251);
    int randomNum2 = rand.nextInt(251);
    int randomNum3 = rand.nextInt(251);
    Color color = new Color(randomNum1, randomNum2, randomNum3);
    setBackground(color);
    super.paint(g);
}

But this will set up a infinite cycle of repaint requests which will eventually consume your CPU cycles and make you PC unusable (not to mention flicker like crazy)...

A better solution might be to override the getBackgroundColor method...

@Override
public Color getBackground() {
    int randomNum1 = rand.nextInt(251);
    int randomNum2 = rand.nextInt(251);
    int randomNum3 = rand.nextInt(251);
    Color color = new Color(randomNum1, randomNum2, randomNum3);
    return color;
}

This will mean that each time this method is called, it will generate a random color. You can then use, some other process, to force the applet to repaint...

Question:

Vertical bars should be filling to the height of the applet. When the top is reached, a new bar should start filling next to the previous. Problem: When the new bar starts filling the previous paint() /bar is cleared

img how it is: http://bayimg.com/DAEoeaagm

img how it should be: http://bayimg.com/dAeOgAaGm

the code:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JApplet;


public class fillingbar extends JApplet implements Runnable{

    int shifting=0,filling=0;
    public void init()
    {
        Thread t= new Thread(this);
        t.start();
        setSize(400,250);
    }

    public void paint(Graphics g)
    {
        super.paint(g);

            g.setColor(Color.GREEN);
            g.fillRect(shifting,getHeight()-filling,20,filling);

            g.setColor(Color.BLACK);
            g.drawRect(shifting, getHeight()-filling, 20, filling);
    }

    public void run()
    {
        while(true)
        {
            repaint();
            try{
                if(shifting<getWidth())
                {
                    if(filling<getHeight())
                        filling+=10;                    
                    else {
                        shifting+=20;
                    filling=0;
                    }
                }       
                Thread.sleep(50);
            }catch(Exception E){
                System.out.println("Exception caught");
            }

        }
    }

}

Answer:

  1. You only draw one rectangle in your paint method, and so it makes sense that only one will show.
  2. If you need to draw more, do so, using a for loop that loops through perhaps a Rectangle ArrayList<Rectangle>.
  3. Another way is to make shifting local and do a bit of simple math inside paintComponent to see what to draw and where. For instance, draw your completed bars inside of a for loop, for (int i = 0; i < filling / getHeight(); i++) {, and your yet to be completed bar up to filling % getHeight().
  4. You should not draw directly within a JApplet but rather in the paintComponent method of a JPanel.
  5. A Swing Timer is easier to use than a thread (for me at least), and can be safer.

For example, this can be created by the code below:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;

import javax.swing.*;

@SuppressWarnings("serial")
public class FillingBar2 extends JApplet {
   @Override
   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               FillingBarPanel fillingBarPanel = new FillingBarPanel();
               add(fillingBarPanel);
               add(new JButton(new StartAction(fillingBarPanel)), BorderLayout.PAGE_END);
               setSize(getPreferredSize());
            }
         });
      } catch (InvocationTargetException | InterruptedException e) {
         System.err.println("Big Problems");
         e.printStackTrace();
      }
   }
}

@SuppressWarnings("serial")
class StartAction extends AbstractAction {
   private FillingBarPanel fillingBarPanel;

   public StartAction(FillingBarPanel fillingBarPanel) {
      super("Start");
      putValue(MNEMONIC_KEY, KeyEvent.VK_S);
      this.fillingBarPanel = fillingBarPanel;
   }

   @Override
   public void actionPerformed(ActionEvent evt) {
      fillingBarPanel.start();
   }
}

@SuppressWarnings("serial")
class FillingBarPanel extends JPanel {
   private static final int BAR_WIDTH = 20;
   private static final int TIMER_DELAY = 100;
   private static final int PREF_W = 400;
   private static final int PREF_H = 250;
   private int filling = 0;
   private Timer timer;

   public FillingBarPanel() {
      timer = new Timer(TIMER_DELAY, new TimerListener());
   }

   public void start() {
      if (timer != null && !timer.isRunning()) {
         timer.start();
      }
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      int shifting = 0;
      for (int i = 0; i < filling / getHeight(); i++) {
         shifting = i * BAR_WIDTH;
         g.setColor(Color.GREEN);
         g.fillRect(shifting, 0, BAR_WIDTH, getHeight());

         g.setColor(Color.BLACK);
         g.drawRect(shifting, 0, BAR_WIDTH, getHeight());
      }
      shifting = BAR_WIDTH * (filling / getHeight());
      g.setColor(Color.GREEN);
      g.fillRect(shifting, getHeight() - (filling % getHeight()), BAR_WIDTH, getHeight());

      g.setColor(Color.BLACK);
      g.drawRect(shifting, getHeight() - (filling % getHeight()), BAR_WIDTH, getHeight());
   }

   private class TimerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent evt) {
         filling += 10;
         repaint();
      }
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

}

Question:

I created an applet wherein I defined a method besides overriding the paint() method that uses the Graphics.drawString() method to display a text on the canvas. The problem I'm having is that I cannot call that method. This is because the method takes a Graphics class object as an argument and I cannot pass a Graphics class object as an argument while calling that function. (The callerMethod() is called in a certain situation.) Please see my code below and help. Thanks.

import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {

    @Override
    public void init() {}

    public void callerMethod() {

        /*HERE I WANT TO CALL myPrintMethod()*/
        myPrintMethod(GRAPHICS OBJECT);
    }

    public static void myPrintMethod(Graphics g) {
        g.drawString("In method myPrintMethod",20,40);
    }

    @Override
    public void paint(Graphics g) {
        g.drawString("In method paint",20,20);
    }
}

Answer:

public class MyApplet extends Applet {
    Graphics g1;

    ---------------

    public void callerMethod() {
            //call myPrintMethod();         
    }

    public static void myPrintMethod() {
        //Now you can paint here also
        g1.drawString("In method myPrintMethod",20,40);
    }

    @Override
    public void paint(Graphics g) {
        g1 = g;
        g.drawString("In method paint",20,20);
    }
}

But this myPrintMethod() should be invoked after the paint(.).

Use Graphics2D that provides more advanced features.

 Graphics2D g2d = (Grapics2D) g;

Question:

I need to write an applet that calculates the squares and cubes of the numbers from 0-10 and draws the resulting values in a table format as follows:

Using a for loop. I made the application and it worked fine. I am using eclipse and when try to declare a string to be a number. I receives errors please help! I have attempted to draw the class from my package and it would not work also.

0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

import java.applet.Applet;
import java.awt.Graphics;

public class countApplet extends Applet 
{

    public void paint(Graphics g) 
    {
        for ( int count = 0 ; count < 10 ; count++ ) 
        {
            count = num1(0); 

            g.drawString( "" , 20  , 20 * ( count + 1 ) );
            g.drawString( "" , 70  , 20 * ( count ^2 ) );
            g.drawString( "" , 120 , 20 * ( count + 1 ) );
        }
    }

}

This is my class I attempt to draw from:

import javax.swing.JOptionPane;
import java.applet.*;
import java.awt.*;

public class calculate
{

    public static void main (String args[])
    {
        int num1 = 0;

        System.out.println("Number" +"\t" +"Square" + "\t" + "Cube");   
        for(int i = 0; i <= 10; i++) 
        {

            System.out.println(i +"\t"+ i * i+"\t" + i* i * i);
        }

    }
}

Maybe a better explanation of how to use Math.sqrt in an applet would help me also?


Answer:

Error in for loop in your countApplet class.Find the below code

for ( int count = 0 ; count < 10 ; count++ ) 
{
    //count = num1(0); 
    g.drawString( String.valueOf(count) , 20  , 20 * ( count + 1 ) );
    g.drawString( String.valueOf(count*count) , 70  , 20 * ( count + 1 ) );
    g.drawString( String.valueOf(count*count*count) , 120 , 20 * ( count + 1 ) );
}

Question:

I've been working on a cell evolution simulation in Java. Just so everyone knows, I'm a beginner/intermediate Java programmer. I know pretty much all the basics and then a little bit, but I don't quite have the skills to write code from scratch. The code I have here is roughly based on a source I found online, I added my own touches and some other pieces I found online as well. It seems to work just fine, except the screen flickers. It seems every time the repaint() is called it flickers, probably clearing and redrawing. It creates something that is practically impossible to look at. There are no errors in my code. I am new to using applets, so if there is a better way to do this, please let me know. How can I stop the screen from flickering? Is there an easy way to buffer the images to prevent that? Here's the class that draws the applet

/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='CellLife.java' width='1920' height='1080'></applet> */

import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;
import java.util.Enumeration;
import java.util.Vector;

public class CellLife extends Applet implements Runnable {
// ========================================================================
// VARIABLES
// ========================================================================

// Data

/** Thread object for CellLife applet */
private Thread m_cellLife = null;

// Static constants

/**
 * the maximum number of creatures in the world. When the number of
 * creatures alive drops below half this, a new one is created to bring the
 * numbers back up.
 */
protected static final int MAX_CREATURES = 60;

// Data

/**
 * A list of the creatures currently alive. Stores CLCreature references.
 */
protected Vector creatures;

/** The world is a rectangle from (0,0) to (limit.x,limit,y) */
protected CL2dVector limit;

/**
 * The number of creatures that have been born since the simulation started
 */
protected long generations;

/** A test creature controllable by the user to allow response testing */
private CLCreature testCreature;

/** space-partitioning structure to speed collision detection */
protected CLBuckets buckets;

// ========================================================================
// METHODS
// ========================================================================

public CellLife() {
    creatures = new Vector();
    limit = new CL2dVector(500.0F, 500.0F);
    generations = 0;

    // initilaize our bucket structure
    float bucketScale = CLCell.RADIUS; // could stretch to root-two times
                                        // this
    buckets = new CLBuckets(bucketScale, (int) Math.ceil(limit.x / bucketScale), (int) Math.ceil(limit.y / bucketScale));
}

public String getAppletInfo() {
    return "Name: Cell Evolution\r\n" + "Author: Josh Marchand\r\n" + "Made in Eclipse";
}

// first time initialazion
public void init() {
    resize((int) limit.x, (int) limit.y);

    for (int i = 0; i < MAX_CREATURES; i++) {
        CLCreature new_creature = new CLCreature();
        new_creature.InitSimple(limit, buckets);
        creatures.addElement(new_creature);
    }
}

public void destroy() {
    // TODO: Place applet cleanup code here
}

public void paint(Graphics g) {
    g.drawString("No. creatures: " + creatures.size(), 0, 11);
    g.drawString("Births: " + generations, 0, 22);

    // draw cells
    for (int i = 0; i < creatures.size(); i++) {
        ((CLCreature) creatures.elementAt(i)).Draw(g);
    }

    // DEBUG: also indicate the contents of the buckets
    // buckets.Draw(g);

    // get all creatures to do their stuff
    CLCreature creature;
    for (int i = 0; i < creatures.size(); i++) {

        creature = (CLCreature) creatures.elementAt(i);

        if (creature.DoTimeStep(g, buckets, limit) && creatures.size() < MAX_CREATURES) {
            // inherit new creature from current
            CLCreature newCreature = new CLCreature();
            newCreature.InheritFrom(creature, buckets, limit);
            creatures.addElement(newCreature);
            generations++;
        }
    }

    // delete the ones that died doing it
    for (Enumeration e = creatures.elements(); e.hasMoreElements();) {
        creature = (CLCreature) e.nextElement();
        if (creature.hasDied) creatures.removeElement(creature);
    }

    // breed nwe creatures if pop. is low
    if (creatures.size() < MAX_CREATURES / 2) {
        // just add one for now,fix later
        CLCreature newCreature = new CLCreature();
        newCreature.InheritFrom((CLCreature) creatures.elementAt((int) Math.random() * creatures.size()), buckets, limit);
        creatures.addElement(newCreature);
        generations++;
    }

}

public void start() {
    if (m_cellLife == null) {
        m_cellLife = new Thread(this);
        m_cellLife.start();
    }
    // TODO: place any additional startup code here
}

public void stop() {
    if (m_cellLife != null) {
        m_cellLife.stop();
        m_cellLife = null;
    }
}

public void run() {
    while (true) {
        try {
            repaint();

            // quick nap here to allow user interface to catch up
            Thread.sleep(100);
        } catch (InterruptedException e) {
            stop();
        }
    }
}

public boolean mouseDown(Event e, int x, int y) {
    // create a single celled creature at specific loc
    testCreature = new CLCreature();
    testCreature.rootCell.location.x = x;
    testCreature.rootCell.location.y = y;
    testCreature.rootCell.type = CLGene.RED;
    creatures.addElement(testCreature);
    buckets.PutCell(testCreature.rootCell);
    return true;
}

public boolean mouseDrag(Event e, int x, int y) {
    testCreature.rootCell.location.x = x;
    testCreature.rootCell.location.y = y;
    return true;
}

public boolean mouseUp(Event evt, int x, int y) {
    creatures.removeElement(testCreature);
    buckets.RemoveCell(testCreature.rootCell);
    return true;
}
}

Thank you all so much for the help, and I'm very sorry about my "noobiness", I am doing my best to teach myself!


Answer:

I would consider using technique called double buffering, where you create an offscreen Graphics object bound to and Image, perform all the drawing on that then paint the result to screen. You can find a handy tutorial on creating graphics from image here. More complete sample can be found here.

Question:

import java.awt.*;
import java.applet.*;
public class rain extends Applet 
{
    int i=0,j=0,k=0;
    AudioClip ac;
    public void init()
    {
        ac=getAudioClip(getCodeBase(),"rain.wav");
        ac.play();
    }
    public void paint(Graphics g)
    {
        setBackground(Color.darkGray);

        g.setColor(Color.gray);
        g.fillOval(100,100,75,25);
        g.fillOval(115,115,75,25);
        g.fillOval(115,85,75,25);
        g.fillOval(165,75,75,25);
        g.fillOval(165,125,75,25);
        g.fillOval(205,115,75,25);
        g.fillOval(205,85,75,25);
        g.fillOval(220,100,75,25);
        g.fillOval(160,95,80,35);

        g.setColor(Color.gray);
        g.fillOval(300,100,75,25);
        g.fillOval(315,115,75,25);
        g.fillOval(315,85,75,25);
        g.fillOval(365,75,75,25);
        g.fillOval(365,125,75,25);
        g.fillOval(405,115,75,25);
        g.fillOval(405,85,75,25);
        g.fillOval(420,100,75,25);
        g.fillOval(360,95,80,35);

        g.setColor(Color.gray);
        g.fillOval(500,100,75,25);
        g.fillOval(515,115,75,25);
        g.fillOval(515,85,75,25);
        g.fillOval(565,75,75,25);
        g.fillOval(565,125,75,25);
        g.fillOval(605,115,75,25);
        g.fillOval(605,85,75,25);
        g.fillOval(620,100,75,25);
        g.fillOval(560,95,80,35);

        g.setColor(Color.gray);
        g.fillOval(700,100,75,25);
        g.fillOval(715,115,75,25);
        g.fillOval(715,85,75,25);
        g.fillOval(765,75,75,25);
        g.fillOval(765,125,75,25);
        g.fillOval(805,115,75,25);
        g.fillOval(805,85,75,25);
        g.fillOval(820,100,75,25);
        g.fillOval(760,95,80,35);
enter code here
        g.setColor(Color.cyan);

        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,160,100+i,180);
            repaint();
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,200,100+i,220);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,240,100+i,260);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,280,100+i,300);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,320,100+i,340);
        } 
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,360,100+i,380);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,400,100+i,420);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,440,100+i,460);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,480,100+i,500);
        }
        for(int i=0;i<=820;i=i+50)
        {
            g.drawLine(100+i,520,100+i,540);
        }

        g.setColor(Color.black);
        g.fillRect(0,590,1000,100);

        g.setColor(Color.white);

        for(i=0;i<=900;i=i+150)
            {
                g.fillRect(30+i,625,100,25);
            }

        g.setColor(new Color(139,69,19));

        g.fillOval(100,600,35,15);
        g.fillOval(300,600,30,10);
        g.fillOval(500,600,25,10);
        g.fillOval(700,600,35,15);
        g.fillOval(125,650,35,15);
        g.fillOval(175,650,35,15);
        g.fillOval(230,670,35,15);
        g.fillOval(280,640,35,15);
        g.fillOval(340,630,35,9);
        g.fillOval(400,650,35,19);
        g.fillOval(450,610,35,10);
        g.fillOval(500,610,35,18);
        g.fillOval(600,675,35,17);
        g.fillOval(700,675,25,15);
        g.fillOval(710,675,30,15);
        g.fillOval(770,623,40,15);
        g.fillOval(690,655,25,15);
        g.fillOval(830,660,25,15);
        g.fillOval(810,670,23,15);
        g.fillOval(880,613,29,15);
    }
}
/*<applet code=rain height=1000 width=1000>
</applet>*/

How Do I blink the only the for loop part of the program? I want to blink the lines contained in the various for loops. Or please tell any other way for blinking a part of the program..Any help will be dearly appreciated.


Answer:

Let's start with Applets are offically deprecated, see Java Plugin support deprecated and Moving to a Plugin-Free Web for more details.

The next equivalent is Swing, like most GUI frameworks, Swing is single threaded and NOT thread safe, this means, you can't perform blocking or long running actions within their event threads nor should you try to update their states from outside of their event threads

See Concurrency in Swing for more details.

In Swing, that leaves you a few options, probably the simplest would be a Swing Timer, see How to use Swing Timers for more details

Now, strictly speaking, this will change the line color for the objects painted within the loops, making them blink

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private int count = 0;
        private Color lineColor = Color.DARK_GRAY;
        private Color[] lineColors = new Color[]{Color.CYAN, Color.DARK_GRAY};

        public TestPane() {
            Timer timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    count++;
                    lineColor = lineColors[count % 2];
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1000, 1000);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            setBackground(Color.darkGray);

            g2d.setColor(Color.gray);
            g2d.fillOval(100, 100, 75, 25);
            g2d.fillOval(115, 115, 75, 25);
            g2d.fillOval(115, 85, 75, 25);
            g2d.fillOval(165, 75, 75, 25);
            g2d.fillOval(165, 125, 75, 25);
            g2d.fillOval(205, 115, 75, 25);
            g2d.fillOval(205, 85, 75, 25);
            g2d.fillOval(220, 100, 75, 25);
            g2d.fillOval(160, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(300, 100, 75, 25);
            g2d.fillOval(315, 115, 75, 25);
            g2d.fillOval(315, 85, 75, 25);
            g2d.fillOval(365, 75, 75, 25);
            g2d.fillOval(365, 125, 75, 25);
            g2d.fillOval(405, 115, 75, 25);
            g2d.fillOval(405, 85, 75, 25);
            g2d.fillOval(420, 100, 75, 25);
            g2d.fillOval(360, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(500, 100, 75, 25);
            g2d.fillOval(515, 115, 75, 25);
            g2d.fillOval(515, 85, 75, 25);
            g2d.fillOval(565, 75, 75, 25);
            g2d.fillOval(565, 125, 75, 25);
            g2d.fillOval(605, 115, 75, 25);
            g2d.fillOval(605, 85, 75, 25);
            g2d.fillOval(620, 100, 75, 25);
            g2d.fillOval(560, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(700, 100, 75, 25);
            g2d.fillOval(715, 115, 75, 25);
            g2d.fillOval(715, 85, 75, 25);
            g2d.fillOval(765, 75, 75, 25);
            g2d.fillOval(765, 125, 75, 25);
            g2d.fillOval(805, 115, 75, 25);
            g2d.fillOval(805, 85, 75, 25);
            g2d.fillOval(820, 100, 75, 25);
            g2d.fillOval(760, 95, 80, 35);


            g2d.setColor(lineColor);

            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 160, 100 + i, 180);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 200, 100 + i, 220);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 240, 100 + i, 260);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 280, 100 + i, 300);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 320, 100 + i, 340);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 360, 100 + i, 380);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 400, 100 + i, 420);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 440, 100 + i, 460);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 480, 100 + i, 500);
            }
            for (int i = 0; i <= 820; i = i + 50) {
                g2d.drawLine(100 + i, 520, 100 + i, 540);
            }

            g2d.setColor(Color.black);
            g2d.fillRect(0, 590, 1000, 100);

            g2d.setColor(Color.white);

            for (int i = 0; i <= 900; i = i + 150) {
                g2d.fillRect(30 + i, 625, 100, 25);
            }

            g2d.setColor(new Color(139, 69, 19));

            g2d.fillOval(100, 600, 35, 15);
            g2d.fillOval(300, 600, 30, 10);
            g2d.fillOval(500, 600, 25, 10);
            g2d.fillOval(700, 600, 35, 15);
            g2d.fillOval(125, 650, 35, 15);
            g2d.fillOval(175, 650, 35, 15);
            g2d.fillOval(230, 670, 35, 15);
            g2d.fillOval(280, 640, 35, 15);
            g2d.fillOval(340, 630, 35, 9);
            g2d.fillOval(400, 650, 35, 19);
            g2d.fillOval(450, 610, 35, 10);
            g2d.fillOval(500, 610, 35, 18);
            g2d.fillOval(600, 675, 35, 17);
            g2d.fillOval(700, 675, 25, 15);
            g2d.fillOval(710, 675, 30, 15);
            g2d.fillOval(770, 623, 40, 15);
            g2d.fillOval(690, 655, 25, 15);
            g2d.fillOval(830, 660, 25, 15);
            g2d.fillOval(810, 670, 23, 15);
            g2d.fillOval(880, 613, 29, 15);
            g2d.dispose();
        }

    }
}

BUT, what might look better, is you could animate the rain falling...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private final int limit = 100;
        private List<DropLet> droplets = new ArrayList<>(limit);

        public TestPane() {
            for (int index = 0; index < limit; index++) {
                droplets.add(new DropLet(150, 675));
            }
            Timer timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Iterator<DropLet> it = droplets.iterator();
                    while (it.hasNext()) {
                        DropLet dropLet = it.next();
                        if (dropLet.update(675)) {
                            it.remove();
                        }
                    }
                    while (droplets.size() < limit) {
                        droplets.add(new DropLet(150, 150));
                    }
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1000, 1000);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            setBackground(Color.darkGray);

            g2d.setColor(Color.gray);
            g2d.fillOval(100, 100, 75, 25);
            g2d.fillOval(115, 115, 75, 25);
            g2d.fillOval(115, 85, 75, 25);
            g2d.fillOval(165, 75, 75, 25);
            g2d.fillOval(165, 125, 75, 25);
            g2d.fillOval(205, 115, 75, 25);
            g2d.fillOval(205, 85, 75, 25);
            g2d.fillOval(220, 100, 75, 25);
            g2d.fillOval(160, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(300, 100, 75, 25);
            g2d.fillOval(315, 115, 75, 25);
            g2d.fillOval(315, 85, 75, 25);
            g2d.fillOval(365, 75, 75, 25);
            g2d.fillOval(365, 125, 75, 25);
            g2d.fillOval(405, 115, 75, 25);
            g2d.fillOval(405, 85, 75, 25);
            g2d.fillOval(420, 100, 75, 25);
            g2d.fillOval(360, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(500, 100, 75, 25);
            g2d.fillOval(515, 115, 75, 25);
            g2d.fillOval(515, 85, 75, 25);
            g2d.fillOval(565, 75, 75, 25);
            g2d.fillOval(565, 125, 75, 25);
            g2d.fillOval(605, 115, 75, 25);
            g2d.fillOval(605, 85, 75, 25);
            g2d.fillOval(620, 100, 75, 25);
            g2d.fillOval(560, 95, 80, 35);

            g2d.setColor(Color.gray);
            g2d.fillOval(700, 100, 75, 25);
            g2d.fillOval(715, 115, 75, 25);
            g2d.fillOval(715, 85, 75, 25);
            g2d.fillOval(765, 75, 75, 25);
            g2d.fillOval(765, 125, 75, 25);
            g2d.fillOval(805, 115, 75, 25);
            g2d.fillOval(805, 85, 75, 25);
            g2d.fillOval(820, 100, 75, 25);
            g2d.fillOval(760, 95, 80, 35);

            g2d.setColor(Color.black);
            g2d.fillRect(0, 590, 1000, 100);

            g2d.setColor(Color.white);

            for (int i = 0; i <= 900; i = i + 150) {
                g2d.fillRect(30 + i, 625, 100, 25);
            }

            g2d.setColor(new Color(139, 69, 19));

            g2d.fillOval(100, 600, 35, 15);
            g2d.fillOval(300, 600, 30, 10);
            g2d.fillOval(500, 600, 25, 10);
            g2d.fillOval(700, 600, 35, 15);
            g2d.fillOval(125, 650, 35, 15);
            g2d.fillOval(175, 650, 35, 15);
            g2d.fillOval(230, 670, 35, 15);
            g2d.fillOval(280, 640, 35, 15);
            g2d.fillOval(340, 630, 35, 9);
            g2d.fillOval(400, 650, 35, 19);
            g2d.fillOval(450, 610, 35, 10);
            g2d.fillOval(500, 610, 35, 18);
            g2d.fillOval(600, 675, 35, 17);
            g2d.fillOval(700, 675, 25, 15);
            g2d.fillOval(710, 675, 30, 15);
            g2d.fillOval(770, 623, 40, 15);
            g2d.fillOval(690, 655, 25, 15);
            g2d.fillOval(830, 660, 25, 15);
            g2d.fillOval(810, 670, 23, 15);
            g2d.fillOval(880, 613, 29, 15);

            for (DropLet dropLet : droplets) {
                dropLet.paint(g2d);
            }

            g2d.dispose();
        }

        public class DropLet {
            private Point location;
            private int yDelta;

            public DropLet(int from, int to) {
                location = new Point(100 + (int)(Math.random() * 800), from + (int)(Math.random() * (to - from)));
                yDelta = (int)(Math.random() * 5) + 1;
            }

            public boolean update(int range) {
                location.y += yDelta;
                return location.y > range;
            }

            public void paint(Graphics2D g2d) {
                g2d.setColor(Color.CYAN);
                g2d.fillOval(location.x - 3, location.y - 3, 6, 6);
            }

        }

    }
}

While this might look some what complex, the concept is very basic. You have a List of DroplLets, which represent the position of a DropLet and the speed at which it drops. You basically loop over the list and update the position of the DropLets until they fall beyond the range you want, at that point they are removed.

The "main loop" maintains a constant number droplets, in this case 100 so that it will continue to rain.

To make things simpler, the positions and speed of the droplets are randomised