Results 1 to 3 of 3
  1. #1
    adlb1300 is offline Member
    Join Date
    Jul 2007
    Posts
    46
    Rep Power
    0

    Default Problem deleting ball from bouncing ball app

    I have a program that will create a new ball each time you click the add ball button adds a randomly colored ball to the window. Problem is I know want to create a button that will delete a ball when it is clicked. I have tried a number of things but to no avail. Below is the code I have and I was hoping someone could look it over and see if they can find what I'm missing.

    Thanks

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    public class BounceBall{
        
        public static void main(String[] args) {
            
            JFrame frame = new BounceFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocation(300,300);
            frame.setVisible(true);
        }
    }
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    
    class BounceFrame extends JFrame {
    
        private BallCanvas canvas;
        public static final int WIDTH = 450;
        public static final int HEIGHT = 350;
    
        
        public BounceFrame() {
            setSize(WIDTH, HEIGHT);
            setTitle("BounceThread");
            
            Container contentPane = getContentPane();
            canvas = new BallCanvas();
            contentPane.add(canvas, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            addButton(buttonPanel, "Add Ball",
                    new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    addBall();
                }
            });
            
            addButton(buttonPanel, "Delete Ball",
                    new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                          delBall();
                    }
            });
            
            addButton(buttonPanel, "Exit",
                    new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    System.exit(0);
                }
            });
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
        }
        
        public void addButton(Container c, String title,
                ActionListener listener) {
            JButton button = new JButton(title);
            c.add(button);
            button.addActionListener(listener);
        }
        
        public void addBall() {
            BouncingBall b = new BouncingBall(canvas);
            canvas.add(b);
            BallThread thread = new BallThread(b);
            thread.start();
        }
        
        public void delBall(){
            BouncingBall db = new BouncingBall(canvas);
            canvas.delBall(db);
        }
    }
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    class BallCanvas extends JPanel {
    
        private ArrayList<BouncingBall> balls = new ArrayList<BouncingBall>();
        
        public void add(BouncingBall b) {
            balls.add(b);
        }
        
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            for (int i = 0; i < balls.size(); i++) {
                BouncingBall b = (BouncingBall)balls.get(i);
                b.draw(g2);
            }
        }
    
        public void delBall(BouncingBall db) {
            balls.remove(db);
        }
        
    }
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    class BouncingBall {
        
        private Component canvas;
        private static final int XSIZE = 15;
        private static final int YSIZE = 15;
        private int x = 0; 
        private int y = 0; 
        private int dx;
        private int dy;
        Color color;
        
        public BouncingBall(Component c) {
            canvas = c;
            color = getColor();
            dx = getSpeed();
            dy = getSpeed();
        }
        
        public void draw(Graphics2D g2) {
        
            g2.setColor(color); 
            g2.fillOval(x,y,15,15);   // adds color to circle
            g2.drawOval(x,y,15,15);   // draws circle
            
        }
        
        public void move() {
            x += dx;
            y += dy;
            if (x < 0) {
                x = 0;
                dx = -dx;
            }
            if (x + XSIZE >= canvas.getWidth()) {
                x = canvas.getWidth() - XSIZE;
                dx = -dx;
            }
            if (y < 0) {
                y = 0;
                dy = -dy;
            }
            if (y + YSIZE >= canvas.getHeight()) {
                y = canvas.getHeight() - YSIZE;
                dy = -dy;
            }
            
            canvas.repaint();
        }
        
        private Color getColor() {
            int rval = (int)Math.floor(Math.random() * 256);
            int gval = (int)Math.floor(Math.random() * 256);
            int bval = (int)Math.floor(Math.random() * 256);
            return new Color(rval, gval, bval);
       }
        
        private int getSpeed() {
            return 10 + (int)Math.floor(Math.random() * 4);
        }
    }
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    class BallThread extends Thread {
        
        private BouncingBall b;
        boolean keepBouncing = true;
        
        public BallThread(BouncingBall aBall) { 
            b = aBall; 
        }
        
        public void run() {
            try {
                while(keepBouncing){
    //            for (int i = 1; i <= 1000; i++) {
                    b.move();
                    sleep(50);
                }
            } catch (InterruptedException exception) {
                keepBouncing = false;
            }
        }
        
    }

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    You will need to add a MouseListener to the BallCanvas and run through the BouncingBalls to see if the user has clicked on any of them. When you get a reference to a selected ball you can remove it from the BallCanvas list. The other detail is that each BouncingBall has an animation thread running. Ideally, we would stop and eliminate this as we remove the ball from the view (BallCanvas). I refactored the class structure/design to facilitate this.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
     
    public class BounceBallAgain extends MouseAdapter implements ActionListener {
        BallCanvas canvas = new BallCanvas();
        BouncingBall selectedBall = null;
    
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("ADD BALL"))
                addBall();
            if(ac.equals("DELETE BALL"))
                delBall();
            if(ac.equals("EXIT"))
                System.exit(0);
        }
    
        private void addBall() {
            BouncingBall bb = new BouncingBall(canvas);
            canvas.add(bb);
            bb.start();
        }
    
        public void delBall() {
            if(selectedBall != null) {
                selectedBall.stop();
                canvas.delBall(selectedBall);
                selectedBall = null;
                canvas.repaint();
            }
        }
    
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            BouncingBall[] balls = canvas.getBalls();
            for(int j = 0; j < balls.length; j++) {
                if(balls[j].contains(p)) {
                    if(selectedBall != null)
                        selectedBall.setSelected(false);
                    selectedBall = balls[j];
                    selectedBall.setSelected(true);
                    break;
                }
            }
        }
    
        private JPanel getButtonPanel() {
            String[] ids = { "Add Ball", "Delete Ball", "Exit" };
            JPanel panel = new JPanel();
            for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setActionCommand(ids[j].toUpperCase());
                button.addActionListener(this);
                panel.add(button);
            }
            return panel;
        }
    
        public static void main(String[] args) {
            BounceBallAgain test = new BounceBallAgain();
            test.canvas.addMouseListener(test);
            final int WIDTH = 450;
            final int HEIGHT = 350;
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(test.canvas);
            frame.getContentPane().add(test.getButtonPanel(), "Last");
            frame.setSize(WIDTH, HEIGHT);
            frame.setLocation(200,200);
            frame.setVisible(true);
        }
    }
    
    class BallCanvas extends JPanel {
        private List<BouncingBall> balls = new ArrayList<BouncingBall>();
    
        public void add(BouncingBall b) {
                balls.add(b);
        }
    
        public void delBall(BouncingBall db) {
            balls.remove(db);
        }
    
        public BouncingBall[] getBalls() {
            int size = balls.size();
            return balls.toArray(new BouncingBall[size]);
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            for (int i = 0; i < balls.size(); i++) {
                BouncingBall b = (BouncingBall)balls.get(i);
                b.draw(g2);
            }
        }
    }
     
    class BouncingBall implements Runnable {
        private Component canvas;
        private static final int XSIZE = 15;
        private static final int YSIZE = 15;
        private int x = 0;
        private int y = 0;
        private int dx;
        private int dy;
        Color color;
        boolean selected = false;
        Thread thread;
        boolean keepBouncing = false;
    
        public BouncingBall(Component c) {
            canvas = c;
            color = getColor();
            dx = getSpeed();
            dy = getSpeed();
        }
    
        public void draw(Graphics2D g2) {
            g2.setColor(color); 
            g2.fillOval(x,y,30,30);   // adds color to circle
            if(selected)
                g2.setPaint(Color.magenta);
            g2.drawOval(x,y,30,30);   // draws circle
        }
    
        public void start() {
            if(!keepBouncing) {
                keepBouncing = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
            }
        }
    
        public void stop() {
            keepBouncing = false;
            if(thread != null)
                thread.interrupt();
            thread = null;
        }
    
        public void run() {
            try {
                while(keepBouncing) {
                    move();
                    Thread.sleep(50);
                }
            } catch(InterruptedException e) {
                System.out.println("interruption");
                keepBouncing = false;
            }
        }
        
        private void move() {
            x += dx;
            y += dy;
            if (x < 0) {
                x = 0;
                dx = -dx;
            }
            if (x + XSIZE >= canvas.getWidth()) {
                x = canvas.getWidth() - XSIZE;
                dx = -dx;
            }
            if (y < 0) {
                y = 0;
                dy = -dy;
            }
            if (y + YSIZE >= canvas.getHeight()) {
                y = canvas.getHeight() - YSIZE;
                dy = -dy;
            }
            canvas.repaint();
        }
    
        public boolean contains(Point p) {
            int w = 2*XSIZE;
            int h = 2*YSIZE;
            return new Ellipse2D.Double(x,y,w,h).contains(p);
        }
    
        public void setSelected(boolean selected) {
            this.selected = selected;
        }
        
        private Color getColor() {
            int rval = 50 + (int)Math.floor(Math.random() * 206);
            int gval = 50 + (int)Math.floor(Math.random() * 206);
            int bval = 50 + (int)Math.floor(Math.random() * 206);
            return new Color(rval, gval, bval);
        }
    
        private int getSpeed() {
            return 1 + (int)Math.floor(Math.random() * 4);
        }
    }

  3. #3
    adlb1300 is offline Member
    Join Date
    Jul 2007
    Posts
    46
    Rep Power
    0

Similar Threads

  1. Multiple bouncing balls
    By Algar in forum AWT / Swing
    Replies: 2
    Last Post: 04-24-2008, 09:35 PM
  2. bouncing ball issue
    By adam405 in forum New To Java
    Replies: 1
    Last Post: 03-18-2008, 04:48 AM
  3. How do I make My ball to move randomly?
    By whdbstjr90 in forum New To Java
    Replies: 4
    Last Post: 12-31-2007, 06:32 PM
  4. Bouncing Ball Just Suddenly Stops Mid Bounce
    By adlb1300 in forum Java 2D
    Replies: 1
    Last Post: 12-03-2007, 03:58 PM
  5. Replies: 2
    Last Post: 12-01-2007, 08:48 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •