swing - Creating my own paint method in java -


i want create method creates 5 balls on panel. can please me around using paint component method or creating own draw method. can see bellow, have paint component method loop loop 5 , create ball in random location, unfortunately 1 ball being created.

import java.awt.*; import java.util.random; import javax.swing.*;  public class allballs extends jpanel {     int number_ball=5;     int x,y;     graphics g;     allballs(){         random r = new random();         x=r.nextint(320);         y=r.nextint(550);     } public static jframe frame;     public static void main(string[] args) {         allballs a= new allballs();         frame= new jframe("bouncing balls");         frame.setsize(400,600);         frame.setdefaultcloseoperation(frame.exit_on_close);         frame.setvisible(true);         frame.add(a);     }      @override     protected void paintcomponent(graphics g) {         super.paintcomponent(g);         for(int i=0;i<number_ball;i++){             g.filloval(x, y, 30, 30);         }         repaint();     }  } 

in paintcomponent method, created loop in wanted 5 ball created, 1 being created on screen.

recommendations per comments:

  1. get rid of graphics g variable hurt you.
  2. consider creating non-gui ball class, 1 not extend swing component , has own paint(graphics) method.
  3. if need 5 balls, create array of ball objects in allballs class.
  4. in paintcomponent, iterate through balls painting each 1 calling paint or draw method (whatever name method).
  5. if need move balls, in swing timer moves balls , calls repaint(). whatever do, not call repaint() within paintcomponent method results in bastardization of method, , results in uncontrolled animation. method should painting , painting , not animation or code logic. use swing timer instead.
  6. also don't randomize ball locations within paintcomponent, recommendation made in now-deleted answer. again, paintcomponent should painting , painting , not program logic or change state of class. randomization should within swing timer or game loop.

for example:

import java.awt.color; import java.awt.dimension; import java.awt.graphics; import java.awt.graphics2d; import java.awt.renderinghints; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.util.arraylist; import java.util.list; import java.util.random; import javax.swing.*;  @suppresswarnings({"serial", "unused"}) public class ballimages extends jpanel {    private static final int pref_w = 800;    private static final int pref_h = pref_w;    private static final int ball_count = 15;    private static final color[] colors = { color.red, color.black, color.blue,          color.cyan, color.green, color.orange, color.pink, color.white,          color.magenta, color.yellow };    private static final int min_speed = 2;    private static final int max_speed = 10;    private static final int min_width = 10;    private static final int max_width = 30;    private static final int timer_delay = 15;    private list<ball> balls = new arraylist<>();    private random random = new random();     public ballimages() {       (int = 0; < ball_count; i++) {          int ballwidth = min_width + random.nextint(max_width - min_width);          color ballcolor = colors[random.nextint(colors.length)];          int ballx = ballwidth / 2 + random.nextint(pref_w - ballwidth / 2);          int bally = ballwidth / 2 + random.nextint(pref_h - ballwidth / 2);          double direction = 2 * math.pi * math.random();          double speed = min_speed + random.nextint(max_speed - min_speed);          ball ball = new ball(ballwidth, ballcolor, ballx, bally, direction,                speed);          balls.add(ball);       }        new timer(timer_delay, new timerlistener()).start();    }     @override    protected void paintcomponent(graphics g) {       super.paintcomponent(g);       graphics2d g2 = (graphics2d) g;       g2.setrenderinghint(renderinghints.key_antialiasing,             renderinghints.value_antialias_on);       (ball ball : balls) {          ball.draw(g2);       }    }     @override    // set component's size in safe way    public dimension getpreferredsize() {       if (ispreferredsizeset()) {          return super.getpreferredsize();       }       return new dimension(pref_w, pref_h);    }     private class timerlistener implements actionlistener {       @override       public void actionperformed(actionevent e) {          if (!ballimages.this.isdisplayable()) {             ((timer) e.getsource()).stop();          }          (ball ball : balls) {             ball.move(pref_w, pref_h);          }          repaint();       }    }     private class ball {       private int width;       private color color;       private double x;       private double y;       private double direction;       private double speed;       private double deltax;       private double deltay;        public ball(int width, color color, int x, int y, double direction,             double speed) {          this.width = width;          this.color = color;          this.x = x;          this.y = y;          this.direction = direction;          this.speed = speed;           deltax = speed * math.cos(direction);          deltay = speed * math.sin(direction);       }        public int getwidth() {          return width;       }        public color getcolor() {          return color;       }        public double getx() {          return x;       }        public double gety() {          return y;       }        public double getdirection() {          return direction;       }        public double getspeed() {          return speed;       }        public void draw(graphics2d g2) {          g2.setcolor(color);          int x2 = (int) (x - width / 2);          int y2 = (int) (y - width / 2);          g2.filloval(x2, y2, width, width);       }        public void move(int containerwidth, int containerheight) {          double newx = x + deltax;          double newy = y + deltay;           if (newx - width / 2 < 0) {             deltax = math.abs(deltax);             newx = x + deltax;          }          if (newy - width / 2 < 0) {             deltay = math.abs(deltay);             newy = y + deltay;          }           if (newx + width / 2 > containerwidth) {             deltax = -math.abs(deltax);             newx = x + deltax;          }          if (newy + width / 2 > containerheight) {             deltay = -math.abs(deltay);             newy = y + deltay;          }           x = newx;          y = newy;        }    }     private static void createandshowgui() {       ballimages mainpanel = new ballimages();        jframe frame = new jframe("ballimages");       frame.setdefaultcloseoperation(jframe.dispose_on_close);       frame.getcontentpane().add(mainpanel);       frame.setresizable(false);       frame.pack();       frame.setlocationrelativeto(null);       frame.setvisible(true);    }     public static void main(string[] args) {       swingutilities.invokelater(new runnable() {          public void run() {             createandshowgui();          }       });    } } 

Comments