import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; // for JSlider events (ChangeListener) import java.util.Random; public class BouncingBallsWithJSliders // this class is the same as BouncingBallsWithRebound but adds JSliders to control the number of balls and speed { private static int number=25, delay=30; // the number of balls and the Timer's delay will be determined by JSliders in the SliderPanel and this will affect how GraphicsPanel works private static GraphicsPanel gp; // declared here so that SliderPanel can reference gp public static void main(String[] args) { JFrame frame=new JFrame(); frame.setSize(540,540); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SliderPanel sp=new SliderPanel(); gp=new GraphicsPanel(); JPanel p1=new JPanel(new BorderLayout()); // add two JPanels now, put the SliderPanel to the right of the GraphicsPanel p1.add(gp,BorderLayout.CENTER); p1.add(sp,BorderLayout.EAST); frame.add(p1); frame.setVisible(true); } public static class SliderPanel extends JPanel implements ChangeListener // will implement two JSliders to control number of balls and speed of animation { private JSlider numberSlider, speedSlider; // our two JSliders public SliderPanel() { numberSlider=new JSlider(JSlider.VERTICAL,1,50,25); // both JSliders will be vertical, number of balls ranges from 1-50 starting at 25 speedSlider=new JSlider(JSlider.VERTICAL,0,20,11); // speed ranges from 0 to 20 starting at 11, but we will take this int and do 3*(21-int), so for instance numberSlider.addChangeListener(this); // starting at all gives us a delay of 3*(21-11) = 30 speedSlider.addChangeListener(this); // both JSliders ChangeListeners will be handled in this class add(numberSlider); // add both JSliders to this JPanel add(speedSlider); } public void stateChanged(ChangeEvent e) // A JSlider was moved { if(e.getSource()==numberSlider) // if numberSlider was moved, get its new position, subtract the current number of balls from this gp.resetNumber(numberSlider.getValue()-number); // and send this change to gp's resetNumber method else if(e.getSource()==speedSlider) // otherwise the speedSlider was moved { delay=3*(21-speedSlider.getValue()); // reset delay accordinatly gp.resetSpeed(); // and call gp's resetSpeed which resets the Timer's delay } } } public static class GraphicsPanel extends JPanel implements ActionListener { private BouncingBall[] balls; private Random generator; private Timer t; public GraphicsPanel() { generator=new Random(); balls=new BouncingBall[50]; // change this to 50 to allow for more balls to be added, we start with number=25 for(int i=0;i0) for(int i=0;i