Multiple bouncing balls thread issue

后端 未结 2 2222
梦谈多话
梦谈多话 2020-11-27 22:59

I created a program that makes multiple bouncing balls with random color, speed and radius. When user clicks on the screen a new random ball should appear and move around sc

2条回答
  •  囚心锁ツ
    2020-11-27 23:18

    You Can try this alternate Java Programm for bouncing 10 multi-colored balls on a single "START" button.....

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javaimage.io.*;
    
    class Thr extends Thread
    {
        boolean up=false;
        Ballbounce parent;
        int top,left;
        Color c;
    
        Thr(int t,int l,Color cr,ex5 p)
        {
            top=l;
            if(top > 170)
            top=170-t/8;
            left=t;
            c=cr;
            parent=p;
        }
    
        public void run()
        {
        try
        {
            while(true)
            {
                Thread.sleep(37);
                if(top >= 188)
                up=true;
                if(top <= 0)
                up=false;
                if(!up)
                top=top+2;
                else
                top=top-2;
                parent.p.repaint();
            }
        }catch(Exception e){}
    }
    }
    
        class Ballbounce extends JFrame implements ActionListener
    {
    int top=0,left=0,n=0,radius=50;
    Color C[]={Color.black,Color.cyan,Color.orange,Color.red,Color.yellow,Color.pink,Color.gray,Color.blue,Color.green,Color.magenta};
    Thr t[]=new Thr[10];
    GPanel p;
    JButton b;
    Panel  p1;
    
    Ballbounce()
    {
    setSize(700,300);
    setVisible(true);
    setLayout( new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(p=new GPanel(this),BorderLayout.CENTER);
    
    b= new JButton("Start");
    b.addActionListener(this);
    
    
    add(p1=new Panel(),BorderLayout.SOUTH);
    p1.setBackground(Color.lightGray);
    p1.add(b);
    }
    
    public static void main(String args[])
    {
    new Ballbounce();
    }
    
    public void actionPerformed(ActionEvent e)
    {
    t[n]=new Thr(left+(radius+13)*n+29,top+n*25,C[n],this);
    t[n].start();
    n++;
    p.repaint();
    if(n >9)
    b.setEnabled(false);
    }
    }
    
    class GPanel extends JPanel
    {
    Ballbounce parent;
    
    GPanel(Ballbounce p)
    {
     parent=p;
    }
    
    public void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    setBackground(Color.white);
    
    for(int i=0;i< parent.n;i++)
    {
    g.setColor(parent.t[i].c);
    g.fillOval(parent.t[i].left,parent.t[i].top,parent.radius,parent.radius);
    }
    }
    }
    

    I hope you will like it.... If u are unable to understand the code... You can question it anytime...... :) Enjoy the code... :)

提交回复
热议问题