Hi, pple im interested to know how to put a drawn 'image', a combination of a circle and a line into another class?

If i like to draw that 'image' in the void paint() method multiple times, e.g 10. How should i go about doing it?

Below is a sample of my code...

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.Timer;


public class Balloons extends Applet implements MouseListener, ActionListener
{
 // The X-coordinate and Y-coordinate of the last move.
 int xpos, ypos;
 int xsrc, ysrc;

 Color fill, outline;
 
 Button butt1 = new Button("Start");
 
 private Timer timer;
 
 long time = 60000; //60 seconds
 
 int displayTime, i;

  
 int delay = 1000; //milliseconds
  ActionListener timerAction = new ActionListener() {
      
      long x = time - 1000;
      public void actionPerformed(ActionEvent evt) {
         ysrc -= 1;
         
          x -= 1000;
          
         i += 1;
              displayTime = 60 - i;
     
          
          if (x < 0) {
              timer.stop();
            }
        
         repaint();
      }
  };


 public void init()
 {

    fill = Color.red;
    outline = Color.blue;  
    
    butt1.setBackground(Color.yellow);
    add(butt1);
    butt1.addActionListener(this);
    
    /*timer start*/
    timer = new Timer( delay, timerAction);
    
    
   
 
  // Add the MouseListener to your applet
  addMouseListener(this);

 

  this.setBackground(Color.white);
 }

 public void paint(Graphics g)
 {

            // A circle using the oval at 150,310 and 80 pixels diameter
    g.setColor(fill);
    g.fillOval(10, 450+ysrc, 30, 30);
    g.setColor(outline);
    g.drawOval(10, 450+ysrc, 30, 30);
    
   
    g.setColor(fill);
    g.fillRect(25, 480+ysrc, 1, 20);
    g.setColor(outline);
    g.drawRect(25, 480+ysrc, 1, 20);
    
     g.drawString("Timer: ("+displayTime+") seconds", 10, 10);
  
    

}

     /*mousemoved method*/
     public void mouseMoved(MouseEvent me) {}

     //method called when mouse is being dragged
     public void mouseDragged(MouseEvent me) {}

     // This method will be called when the mouse has been clicked.
     public void mouseClicked (MouseEvent me) {}
     
     public void mousePressed (MouseEvent me) {}
 
     public void mouseReleased (MouseEvent me) {} 
 
     public void mouseEntered (MouseEvent me) {}

     public void mouseExited (MouseEvent me) {} 
 
      public void actionPerformed(ActionEvent click){
        	
         timer.start();
        
        }
    

}

Dani AI

Generated

Two issues are showing up in this thread: scope/architecture (why x[] is not visible in mouseClicked) and how to organize the drawing so you can draw many balloons cleanly. As suggested, Graphics.translate is one way to reduce repeated positioning, but a better long-term fix is to model each balloon as an object and keep the positions as fields you can access from any method (init, timer, paint, mouse handlers). The current compiler error happens because your int[] x is declared inside balloon(...) and is not visible in mouseClicked(...) — move that state to the applet class (or into Balloon objects) so both paint and mouse handlers can read it.

Example Balloon object (focus on structure and hit-testing):

class Balloon {
  int x, y, w = 30, h = 30;
  Color fill, outline;

  public Balloon(int x, int y, Color f, Color o) { this.x = x; this.y = y; fill = f; outline = o; }

  public void draw(Graphics g) {
    Graphics g2 = g.create();   // isolate transforms/clip
    g2.setColor(fill);
    g2.fillOval(x, y, w, h);
    g2.setColor(outline);
    g2.drawOval(x, y, w, h);
    g2.dispose();
  }

  public void move(int dy) { y += dy; }

  public boolean contains(int mx, int my) { return mx >= x && mx <= x + w && my >= y && my <= y + h; }
}

How to use them in the applet: create an array or ArrayList of Balloon in the applet (declare it as a field), initialize in init(), call each draw(g) from paint(), update positions in the timer, and in mouseClicked iterate the balloons and call contains(...). Only increment MissScore if no balloon matched; increment HitScore and break when one matches. Also avoid reusing the same variable name i for different purposes (class field vs loop variable) — that causes confusing bugs.

A few extra tips: do not let repeated g.translate(...) accumulate (use g.create() and dispose()), keep painting free of heavy logic (treat paint as view-only), prefer Swing conventions if you use javax.swing.Timer, and note that applets are obsolete in modern Java/browser environments. For painting details and best practices see the Java painting tutorial: Painting in AWT and Swing.

Recommended Answers

All 2 Replies

Override the paint method and use the translate method of the Graphics object. Remember that translate(100,100) doesn't mean goto point 100,100. It means move to the right 100 and move down 100.

public void paint(Graphics g)
 {
	//draw circle
	drawCircle(g);

	//move left and down by 100
	g.translate(100,100);

	//draw another circle
	drawCircle(g);

	//move left and down by 100
	g.translate(100,100);

	//draw another circle
	drawCircle(g);
}

private void drawCircle(Graphics g)
{
	g.setColor(fill);
	g.fillOval(0, 0, 30, 30);
	g.setColor(outline);
	g.drawOval(0, 0, 30, 30);
    
}

For more help,

Thanks for the help NPH, it has helped me a lot.
i am now having problems trying to get the a variable from my 'public void balloon' method. The variable is array x. I like to call the variable in my 'mouseclick' method but i am unable to do so. An error " x is not public in java.awt.Component; cannot be accessed from outside the package".

I would also like to ask for help or examples in objects and classes. Im thinking of setting the balloon method into another class. But i do not know how to go about in doing so. If possible, how do i access the methods in the newly created balloon class too?

I like to seek some help in this . Thank you.


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.Timer;





public class Game extends Applet implements MouseListener, ActionListener
{



 // The X-coordinate and Y-coordinate of the last move.
 int xpos, ypos;
 
 int ysrc;
 
 Color fill, outline;


 
 
 Button butt1 = new Button("Start");
 
 private Timer timer;
 
 long time = 60000; //60 seconds
 
 int displayTime, i;
 
 boolean clicked, OnImage;
 
 int HitScore, MissScore;
 
 
 
 int delay = 1000; //milliseconds
  ActionListener timerAction = new ActionListener() {
      
      long x = time - 1000;
      public void actionPerformed(ActionEvent evt) {
         ysrc -= 1;
         
          x -= 1000;       
          
         i += 1;
         displayTime = 60 - i;   
          
          if (x < 0) {
              timer.stop();
            }
        
         repaint();
      }
  };


 public void init()
 {
     
     fill = Color.red;
     outline = Color.blue;  
    
    
    butt1.setBackground(Color.yellow);
    add(butt1);
    butt1.addActionListener(this);
    
    /*timer start*/
    timer = new Timer( delay, timerAction); 
   
  // Add the MouseListener to your applet
  addMouseListener(this);

  this.setBackground(Color.white);
 }

 public void paint(Graphics g)
 {

    
    
  
     
     balloon(g);    
     
     g.drawString("Timer: ("+displayTime+") seconds", 10, 10);
     g.drawString("HITS: ("+HitScore+"), MISS: ("+MissScore+")", 10, 20);
  
    

}

public void balloon(Graphics g) {

        int [] x;
        x = new int[10];
   
    
    for( int i = 0; i<10; i++){
    
        int count;
        count = 40;
        int increment = count*i;
        if(increment == 0){
            increment = 40;
        }
        x[i] = increment;
        
    g.setColor(fill);
    g.fillOval(x[i], 450+ysrc, 30, 30);
    g.setColor(outline);
    g.drawOval(x[i], 450+ysrc, 30, 30);
    
         }
       }


     /*mousemoved method*/
     public void mouseMoved(MouseEvent me) {}

     //method called when mouse is being dragged
     public void mouseDragged(MouseEvent me) {}

     // This method will be called when the mouse has been clicked.
     public void mouseClicked (MouseEvent me) {
          
     xpos = me.getX();
     ypos = me.getY();
     
 
      
        if( xpos > x[i] && xpos < x[i] + 30 && ypos > 450+ysrc && ypos < 450+ysrc + 30 ) {
              OnImage = true;

            } else {
                OnImage =false;
                   }
                
                
                   
                   //if OnImage is true set the hit score to increment by 1 else increment misses by 1
                if( OnImage ) {
                    HitScore += 1;
                        } else {
                        MissScore += 1;
                            }
        
        }
     
     public void mousePressed (MouseEvent me) {}
 
     public void mouseReleased (MouseEvent me) {} 
 
     public void mouseEntered (MouseEvent me) {}

     public void mouseExited (MouseEvent me) {} 
 
      public void actionPerformed(ActionEvent click){
            
         timer.start();
        }
        
 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.