GetDefaultToolkit().beep();

java.awt.Toolkit.getDefaultToolkit().beep();
I,ve looked in the api but not very clear(dohhhhhhhhhhh).
can,t make it work,any help appreciated.
basic question to you guys but do i need to import the package or is this part of awt anyway.code to show me it working appreciated
very very new to java
Thanks again
cheers

java.awt.Toolkit.getDefaultToolkit().beep();This should work without imports as you are giving the full class name.
I would check that the computer you are running on is capable of beeping.
On a PC this would come out of the crappy built in speaker and not the audio outputs.

Similar Messages

  • Substitute of java.awt.ToolKit.getDefaultToolKit.beep()

    Hello everybody. I am designing a Swing Application and there I am using java.awt.ToolKit.getDefaultToolKit.beep() method to generate sound in various operations. I want to know is it possible to generate own sound as a substitute of this method? I think it is possible. How can I do this? Thank you.

    Thank you for giving reply.
    As I wish to play .mp3 file I had downloaded an API from Javalobby . I tried it, here is my code :
    package player;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.SourceDataLine;
    * @author Tanmoy
    * @Super Scientific Calculator
    * @version 1.2010
    public class Player {
         private File audioFile;
         public Player(String path) {
              this.audioFile = new File(path);
         public void play() {
              AudioInputStream din = null;
              try {
                   AudioInputStream in = AudioSystem.getAudioInputStream(audioFile);
                   AudioFormat baseFormat = in.getFormat();
                   AudioFormat decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                        false);
                   din = AudioSystem.getAudioInputStream(decodedFormat, in);
                   DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
                   SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                   if (line != null) {
                        line.open(decodedFormat);
                        byte[] data = new byte[4096];
                        line.start();
                        int nBytesRead;
                        while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                             line.write(data, 0, nBytesRead);
                        line.drain();
                        line.stop();
                        line.close();
                        din.close();
              } catch (Exception e) {
              } finally {
                   if (din != null) {
                        try {
                             din.close();
                        } catch (IOException e) {
    }And the calling, piece of code is :
    try {
                                  Parser parser = new Parser(parsingString, displayPanel.getCurrentBase(),
                                       displayPanel.getCurrentBase(), displayPanel.getTrigoMode(),
                                       displayPanel.getScale());
                                  String output = parser.solve();
                                  displayPanel.outputTextField.setText(output);
                                  displayPanel.outputTextField.setCaretPosition(displayPanel.outputTextField.getText().length());
                                  displayPanel.charLabel.setText((Integer.toString(output.length())));
                                  if (message == null) {
                                       message = "No Exception";
                             } catch (InvalidSyntaxException invalidSyntaxException) {
                                  message = invalidSyntaxException.getMessage();
                                  JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
                                  new Player("/resources/what_the_hell.mp3").play();
                                  displayPanel.outputTextField.setText("0");
                                  displayPanel.charLabel.setText("0");
                             }But I can not able to here the sound.
    What to do now?
    Thank you.

  • Toolkit.getDefaultToolkit().beep() does not beep!

    Hi,everyone:
    I met a problem when I used Toolkit.getDefaultToolkit().beep() .
    When running, no beep can be heard!
    My Environment is as follows:
    Hardware: Dell dimension 2400
    OS : Windows 2003 Enterprise Edition
    JDK : J2SDK1.4.2
    Code :
    Toolkit.getDefaultToolkit().beep();
    (In java application)
    Does My enviornment not support this operation? Can anyone tell me?
    Thank you.

    Yes, its a bit buggy. Does this work for you?
    ** Will you please tell me where to find evidence that this is a bit buggy?
    Thank you.
    System.out.print ( "\007" );In my java application, System.out.print ( "\007" ) works.
    ** But when I write it in my applet, no beep can be heard!
    import java.applet.*;
    import java.awt.*;
    public class MyBeepApplet extends Applet
        int cx = 50;
        int cy = 50;
        String msg="";
        public boolean mouseDown(Event e, int x, int y)
            msg = " Beep?";
            cx = x;
            cy = y;   
            for(int i=0; i<260;i++){
                System.out.print("\007");
                System.out.flush();
            repaint();      
            return true;
        public void paint(Graphics g)
            g.drawString(msg, cx,cy);
    }

  • How to prevent the Toolkit.getDefaultToolkit().beep() in JTextField

    Hi,
    I use the JTextField in my application.
    when the user type value in the field e.g. "123456"
    if you press the backspace 5 times the value will be "1" , pressing it again results with ""
    now.....
    pressing it again results a system beep.
    I want to prevent this beep how can I do it??
    thanks

    textField.getDocument().addDocuemntListener(docListener);
    Then implement the removeUpdate(DocumentEvent evt)
    Hope this helps
    Sai Pullabhotla

  • How to make beep by PC speaker in java

    hello,everybody:
    I know that can make pc speaker produce beep voice in c language through use ascII--007,but how to realize it in java application.Please help me,thank you.

    Hi, try this
    Toolkit.getDefaultToolkit().beep();this also works on some systems
    System.out.print( '\u0007' );   
    System.out.print( '\007' );   
    System.out.print( (char)0x07 );hope this helps
    AA

  • System Beep using Java

    I want to get system beep sound using java
    System.out.println("\007");using I can play it. but I 'm using Eclipse IDE. There that is not work. I think i want to write shell java programm and there I want to run some C code. But I don't knoww it properly.
    if aany one can do that . help me.
    thank you....

    Problem is I can't play system beep in any IDE. that mean java.awt.Toolkit.getDefaultToolkit().beep(); is not work in Eclipse IDE.
    may i can do it like this?
    Runtime r = Runtime.getRuntime(); //get runtime information
                 try
                 Process Child = r.exec("cmd.exe") ; //execute command
                 BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(Child.getOutputStream()));
                 outCommand.write("cmd.exe");
                 outCommand.flush();
                 catch(IOException eds)
                 { //handle exec failure
                 System.out.println("ERROR: exec failure"+eds);
                 //System.exit(11); //exit application with exit code 11
                 }

  • Beep in an applet

    Hi !
    I would like to find a portable way, if possible without an audio file, to make a "bip" in an applet.
    Is printing the character with code 07 to standard output, or standard error, could
    work and be portable enough ?
    Thanks,
    -- Alexis

    Not sure what you mean here, but you can use the client resources without any added overhead with;-
    if(conition=error); // catch(Exception ...
    java.awt.Toolkit.getDefaultToolkit().beep();

  • I want to Beep the user

    I have a case where the user drills down into lower and lower levels of detail. When the user gets to the leaf level and they try to drill down even further I display an error message in a message list component. I would also like to make some kind of beeping noise. How do I make a beeping noise in JSC?

    You definitely don't want to run Toolkit.getDefaultToolkit().beep().
    That's java code, which will be run on the server! Everytime a user makes a mistake your server will beep - alerting you, not the user :)
    To get the browser to beep you'll need to use javascript.
    Google "javascript beep", but I think it's as easy as calling "Beep()" from javascript code.
    -- Tor
    http://blogs.sun.com/tor

  • System beep ?

    Hi guys,
    Any body know how to make the system speaker beep in java?
    Like, was it "sound" in basic - arrr the times....
    Thanks
    Tom

    java.awt.Toolkit.getDefaultToolkit().beep() ?java.util.Toolkit.getDefaultToolkit().beep(); Why not awt?

  • Can't Get A Beep

    I have to get a beep from the system speaker for a warning alert. It makes no difference if I use Toolkit.getDefaultToolkit().beep(); or System.out.print("\007"); System.flush(); I'm using j2sdk1.4.1_0 on WIn98SE. Tried on 3 different systems - no luck. Any insight would be helpful.
    BTW, POST gives beeps on at least two of those three systems, so I know the speaker works.

    Try this:
    Enter the following command at the MS-DOS Command Prompt:
    echo <Ctrl+G><ENTER>
    It is shown in the screen as
    echo ^G
    If it does not beep, your Java program won't beep as well.

  • Can I create Beep sound for 1min continuously??

    Hi,
    Can any one plz tell me How Can I create Beep sound for 1min continuously.Now I can create Beep sound only once by below code.Eagerly waiting for someone reply.
    Toolkit.getDefaultToolkit().beep();
    Regards
    Bikash

    Try this
    int delay = 100; //milliseconds
    Timer t=new Timer(delay, new ActionListener() {
         int count=1;
         public void actionPerformed(ActionEvent evt) {
         if(count<=59)
         java.awt.Toolkit.getDefaultToolkit().beep();
         count++;
         else
      return;
    t.start();

  • Beep sound?

    How can I make a beep sound (for example as a cue to the operator when an invalid key is pressed)?
    AWT has Toolkit.getDefaultToolkit().beep().
    SWT has ... getDisplay().beep();
    How can accomplish the same in FX? (The AWT call fails in an FX environment.)

    abg wrote:
    Toolkit.getDefaultToolkit().beep();
    works for me.
    alexThe fact if it works was not the question. But you're still right in a way - using the old AWT beep() functionality is still the way to go it seems. Or play your own sound through an AudioClip for example.
    Apparently there is a feature request for a beep through the JavaFX API:
    http://stackoverflow.com/questions/10636194/java-fx-2-alert-sound
    http://javafx-jira.kenai.com/browse/RT-21634
    (which has been rejected it seems).

  • What the heck am I doing wrong???

    The error message I'm getting is the following: "week4_herbie must be defined in its own file" The problem that I'm running into is that the programs are supposed to work together. One (week4_herbie) handles the mortgage calculation itself (and set up the GUI) and send the information to the amoritizeFrame program, which is designed to display the amoritization table. The numericTextFrame is to make sure that the variable input is acceptable. Here is the coding:
    week4_herbie
    The Amortization Schedule was constructed with my own class called AmortFrame
    that extends JFrame and a JTextArea that was added to a JScrollPane.
    // Imports needed libraries
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    // Event handling:implements listener interface for receiving action events.
    public class week4_herbie implements ActionListener
         // GUI Components
         JFrame calculatorFrame;
         JPanel calculatorPanel;
         AmortizeFrame amortFrame;   //local class for amortization schedule
         //  user input fields
         //  Loan amount entered as user text input from keyboard
         //  Term (in years) selected from a combo box
         //  Rate (%) selected from a combo box
         numericTextField loan;
         JComboBox rate;
         JComboBox term;
         // set up arrays for the selectable term and rate
        int[] loanTerm = new int[3];
        String[] loanTermString = new String[3];
        double[] loanRate = new double[3];
        String[] loanRateString = new String[3];
        // static variables, belong to class on not an instance
         static String sWindowTitle = "Brian's Week 3 - Mortgage Calculator";
         static String scolHeader = "Payment#\tPayment\tInterest\tCumInterest\tPrincipal\tBalance\n";
         static String slineOut = "________\t_______\t________\t___________\t_________\t_______\n";
         static String sfinalInstructions1 = "\nYou can leave windows open and enter new value or close either window to exit\n";
         JLabel loanLabel,termLabel, rateLabel, pmtLabel;
         JButton calculate;
        public week4_herbie()
              // Before progressing, read in the data
              if(readData())
                   //Create and set up the window.
                   calculatorFrame = new JFrame(sWindowTitle);
                   calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // Set size of user input frame;
                   calculatorFrame.setBounds(0,0,100,100);
                   //Create and set up the panel with 4 rows and 4 columns.
                   calculatorPanel = new JPanel(new GridLayout(4, 4));
                   //Add the widgets.
                   addWidgets();
                   //Set the default button.
                   calculatorFrame.getRootPane().setDefaultButton(calculate);
                   //Add the panel to the window.
                   calculatorFrame.getContentPane().add(calculatorPanel, BorderLayout.
                   CENTER);
                   //Display the window.
                   calculatorFrame.pack();
                   calculatorFrame.setVisible(true);
              }// good data read
        }// end constructor
        private boolean readData()
              boolean isValid = true;
            loanRateString[0] = "5.35%";
            loanRateString[1] = "5.5%";
            loanRateString[2] = "5.75%";
            loanTermString[0] = "7 Years";
            loanTermString[1] = "15 Years";
            loanTermString[2] = "30 Years";
            loanRate[0] = 5.35;
            loanRate[1] = 5.5;
            loanRate[2] = 5.75;
            loanTerm[0] = 7;
            loanTerm[1] = 15;
            loanTerm[2] = 30;
            return isValid;
         }// end readData
        // Creates and adds the widgets to the user input frame.
        private void addWidgets()
            // numericTextField is a JTextField with some error checking for
            // non  numeric values.
            loan = new numericTextField();
            rate = new JComboBox(loanRateString);
              term = new JComboBox(loanTermString);
            loanLabel = new JLabel("Loan Amount", SwingConstants.LEFT);
            termLabel = new JLabel(" Term ", SwingConstants.LEFT);
            rateLabel = new JLabel("  Interest Rate ", SwingConstants.LEFT);
            calculate = new JButton("Calculate");
            pmtLabel  = new JLabel("Monthly Payment", SwingConstants.LEFT);
            //Listen to events from the Calculate button.
            calculate.addActionListener(this);
            //Add the widgets to the container.
            calculatorPanel.add(loan);
            calculatorPanel.add(loanLabel);
            calculatorPanel.add(term);
            calculatorPanel.add(termLabel);
            calculatorPanel.add(rate);
            calculatorPanel.add(rateLabel);
            calculatorPanel.add(calculate);
            calculatorPanel.add(pmtLabel);
            //set label border size
            loanLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            pmtLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        } // end addWidgets
        // Event handling method invoked when an action occurs.
        // Processes each of the fields and includes error checking
        // to make sure each field has data in it and then calculates
        // actual payment.
        public void actionPerformed(ActionEvent event)
            double tamount = 0; //provides floating point for total amount of the loan
            int term1      = 0; //provides int for the term
            double rate1   = 0; //provides floating point for the percentage rate.
            // get string to test that user entered
                String testit = loan.getText();          // get user entered loan amount
                // if string is present
                if(testit.length() != 0)
                   tamount = (double)(Double.parseDouble(testit)); // convert to double
                   // first value valid - check second one, term value
                   // get the index of the item the user selected
                   // then get the actual value of the selection from the
                   // loanTerm array
                   int boxIndex = term.getSelectedIndex();
                   if(boxIndex != -1)
                        term1 = loanTerm[boxIndex];
                        // second value valid - check third one, interest rate
                        // get the index of the item the user selected
                       // then get the actual value of the selection from the
                       // loanRate array
                       boxIndex = rate.getSelectedIndex();
                       // if something is selected in rate combo box
                        if(boxIndex != -1)
                            rate1 = loanRate[boxIndex];
                             // all three values were good so calculate the payment
                        double payment = ((tamount * (rate1/1200)) /
                                              (1 - Math.pow(1 + rate1/1200, -term1*12)));
                        // format string using a mask
                        java.text.DecimalFormat dec = new java.text.DecimalFormat(",###.00");
                        String pmt = dec.format(payment);
                        // change foreground color of font for this label
                        pmtLabel.setForeground(Color.green); //
                        // set formatted payment
                             pmtLabel.setText(pmt);
                             // generate the amortization schedule
                             amortize(tamount, rate1*.01, term1*12, payment);
                        else  //third value was bad
                             Toolkit.getDefaultToolkit().beep(); // invokes audible beep
                             pmtLabel.setForeground(Color.red);  // sets font color
                             pmtLabel.setText("Missing Field or bad value");  // Error Message
                        }// end validate third value
                   else  // second value was bad
                        Toolkit.getDefaultToolkit().beep();
                        pmtLabel.setForeground(Color.red);
                        pmtLabel.setText("Missing Field or bad value");
                   }// end validate second value
              else  // first value was bad
                   Toolkit.getDefaultToolkit().beep();
                   pmtLabel.setForeground(Color.red);
                 pmtLabel.setText("Missing Field or bad value");
              }// end validate first value
        }// end actionPerformed
         // calculate the loan balance and interest paid for each payment over the
         // term of the loan and list it in a separate window - one line per payment.
         public void amortize(double principal, double APR, int term,
                              double monthlyPayment)
              double monthlyInterestRate = APR / 12;
              //double totalPayment = monthlyPayment * term;
              int payment = 1;
              double balance = principal;
              int num = 0;
              double monthlyInterest;
              double cumInterest = 0;
            // if the frame for the amortization schedule has not been created
            // yet, create it.
              if(amortFrame == null)
                 amortFrame = new AmortizeFrame();
              // obtain a reference to our text area in our frame
              // and update this as we go through
              JTextArea amortText = amortFrame.getAmortText();
              // formatting mask
              java.text.DecimalFormat df= new java.text.DecimalFormat(",###.00");
              // set column header
              amortText.setText(scolHeader);
              amortText.append(slineOut);
              // loop through our amortization table and add to
              // JTextArea
              while(num < term)
                   monthlyInterest = monthlyInterestRate * balance;
                   cumInterest += monthlyInterest;
                   principal = monthlyPayment - monthlyInterest;
                   balance -= principal;
                   //Show Amortization Schedule
                   amortText.append(String.valueOf(payment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyPayment));
                   amortText.append("\t ");
                   amortText.append(df.format(monthlyInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(cumInterest));
                   amortText.append("\t ");
                   amortText.append(df.format(principal));
                   amortText.append("\t ");
                   amortText.append(df.format(balance));
                   amortText.append("\n");
                   payment++;
                   num++;
              // print the headers one more time at the bottom
              amortText.append(slineOut);
              amortText.append(scolHeader);
              amortText.append(sfinalInstructions1);
         }// end amortize
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
             //Note this next line only works with JDK 1.4 and higher
            JFrame.setDefaultLookAndFeelDecorated(true);
            week4_herbie calculator = new week4_herbie();
        // main method
        public static void main(String[] args)
             // allow user to set a different file from
             // command line
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }// end classAmoritizeFrame
    import java.awt.*;
    import javax.swing.*;
    // this class provides the frame and the scrolling text area for the
    // amortization schedule
    class AmortizeFrame extends JFrame
         private JTextArea amortText;
         private JScrollPane amortScroll;
         private String sTitle = "Brian's";
         final String sTitle2 = " Amortization Schedule";
         // default constructor
         public AmortizeFrame()
              initWindow();
         // constructor that takes parameter (such as week number)
         // to add extra info to title on frame of window
         public AmortizeFrame(String week)
              sTitle = sTitle + " " + week;
              initWindow();
         }// end constructor
         // helper method that initialized GUI
         private void initWindow()
              setTitle(sTitle + sTitle2);
              setBounds(200,200,550,400);
              Container contentPane=getContentPane();
              amortText = new JTextArea(7,100);
              amortScroll= new JScrollPane(amortText);
              contentPane.add(amortScroll,BorderLayout.CENTER);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         // method to get the text area for users of
         // this frame.  They can then add whatever text they want from the outside
         public JTextArea getAmortText()
              return amortText;
    }// end amortizeFramenumericTextFrame
    * This is a control that subclasses the
    * JTextField class and through a keyboard
    * listener only allows numeric input, decimal point
    * and backspace into the text field.
    * Known Problems!!!:
    * 1) It will not catch if the user
    *    enters two decimal points
    import java.awt.Toolkit;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JTextField;
       A JTextField subclass component that
       only allowing numeric input.  
    class numericTextField extends JTextField
        private void setUpListener()
            addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e)
                            char c = e.getKeyChar();
                    if(!Character.isDigit(c) && c != '.' && c != '\b' && c != '\n' && c != '\177')
                        Toolkit.getDefaultToolkit().beep();
                        e.consume();
        numericTextField(int i)
             super(i);
               setUpListener();
        public numericTextField()
              setUpListener();
    }Thanks for the assist

    Top-level classes (that is, classes not inside other classes) must be defined as public or package-private (the default access level if you do not provide one).
    A public top-level class Foo must be contained in Foo.java.
    A non-public top-level class Foo can be contained in any .java file.

  • Why aren't the Balls Bouncing  ? HELP !

    Dear Java People,
    In doing a program that should have balls bouncing, I can see no balls bouncing !
    Below is the BallDemo class that has the bounce() method and the BouncingBall class that has the characteristics of a bouncing ball.
    There are no compilation errors which makes it a little bit
    difficult to find the error.
    Thank you in advance
    Stan
    import java.awt.*;
    //(d)
    import java.awt.Color;
    import java.util.Random;
    import java.awt.geom.*;
    //ex5.50 (a)
    import java.util.*;
    import java.io.*;
    * Class BallDemo - provides two short demonstrations showing how to use the
    * Canvas class.
    //(a) Change the bounce() method in the BallDemo class to let the user
    //choose how many balls should be bouncing
    //(b) Use a collection to store the balls
    //(c) Place the balls in a row along the top of the canvas.
    public class BallDemo
        private Canvas myCanvas;
        FormattedInput input;
         * Create a BallDemo object. Creates a fresh canvas and makes it visible.
        public BallDemo()
            myCanvas = new Canvas("Ball Demo", 600, 500);
            input = new FormattedInput();
            myCanvas.setVisible(true);
         * This method demonstrates some of the drawing operations that are
         * available on a Canvas object.
        public void drawDemo()
            myCanvas.setFont(new Font("helvetica", Font.BOLD, 14));
            myCanvas.setForegroundColor(Color.red);
            myCanvas.drawString("We can draw text, ...", 20, 50);
            myCanvas.wait(1000);
            myCanvas.setForegroundColor(Color.black);
            myCanvas.drawString("...draw lines...", 60, 70);
            myCanvas.wait(500);
            myCanvas.setForegroundColor(Color.blue);
            myCanvas.drawLine(200, 20, 300, 450);
            myCanvas.wait(500);
            myCanvas.setForegroundColor(Color.blue);
            myCanvas.drawLine(220, 100, 570, 260);
            myCanvas.wait(500);
            myCanvas.setForegroundColor(Color.green);
            myCanvas.drawLine(290, 10, 620, 220);
            myCanvas.wait(1000);
            myCanvas.setForegroundColor(Color.white);
            myCanvas.drawString("...and shapes!", 110, 90);
            myCanvas.setForegroundColor(Color.red);
                    // the shape to draw and move
            int xPos = 10;
            Rectangle rect = new Rectangle(xPos, 150, 30, 20);
            // move the rectangle across the screen
            for(int i = 0; i < 200; i ++) {
                myCanvas.fill(rect);
                myCanvas.wait(10);
                myCanvas.erase(rect);
                xPos++;
                rect.setLocation(xPos, 150);
            // at the end of the move, draw once more so that it remains visible
            myCanvas.fill(rect);
           //ex 5.48
           public void drawFrame()
             Dimension myDimension =new Dimension( myCanvas.getSize());
             //Rectangle rectangle = new Rectangle(10,10,myDimension.width,  myDimension.height);
             //page 136
            Rectangle rectangle = new Rectangle(10,10,580,480);
             myCanvas.fill(rectangle);
         * Simulates two bouncing balls
        public void bounce()
            int ground = 400;   // position of the ground line
            int numberOfBalls = 0;
            myCanvas.setVisible(true);
            ArrayList balls = new ArrayList();
            // draw the ground
            myCanvas.drawLine(50, ground, 550, ground);
            //ex 5.50 (a)
            System.out.println("Type in the number of balls you would like to see bouncing and hit enter");
              numberOfBalls = input.readInt();
             //(b)
             for(int i = 0; i < numberOfBalls; i++)
               //(c) (d)
            Random rg = new Random(255);
             BouncingBall newBall =  new BouncingBall(i + 100, 0, 16, new Color(rg.nextInt(255),rg.nextInt(255),rg.nextInt(255)), ground, myCanvas);
             //add the ball to the ArrayList object
            balls.add(newBall);
           for(int i = 0; i < numberOfBalls; i++)
                  BouncingBall ball = (BouncingBall)balls.get(i);
                  ball.draw();
              // make the balls bounce
              boolean finished =  false;
              while(!finished) {
               myCanvas.wait(50);           // small delay
               ball.move();
                // stop once ball has travelled a certain distance on x axis
                if(ball.getXPosition() >= 550 )
                    finished = true;
            }//move loop
                  ball.erase();
          }//for loop
        }//bounce method
    }//endof class
    ===================================================================
    import java.awt.*;
    import java.awt.geom.*;
    * Class BouncingBall - a graphical ball that observes the effect of gravity. The ball
    * has the ability to move. Details of movement are determined by the ball itself. It
    * will fall downwards, accelerating with time due to the effect of gravity, and bounce
    * upward again when hitting the ground.
    * This movement can be initiated by repeated calls to the "move" method.
    public class BouncingBall
        private static final int gravity = 3;  // effect of gravity
        private int ballDegradation = 2;
        private Ellipse2D.Double circle;
        private Color color;
        private int diameter;
        private int xPosition;
        private int yPosition;
        private final int groundPosition;      // y position of ground
        private Canvas canvas;
        private int ySpeed = 1;                // initial downward speed
         * Constructor for objects of class BouncingBall
         * @param xPos  the horizontal coordinate of the ball
         * @param yPos  the vertical coordinate of the ball
         * @param ballDiameter  the diameter (in pixels) of the ball
         * @param ballColor  the color of the ball
         * @param groundPos  the position of the ground (where the wall will bounce)
         * @param drawingCanvas  the canvas to draw this ball on
        public BouncingBall(int xPos, int yPos, int ballDiameter, Color ballColor,
                            int groundPos, Canvas drawingCanvas)
            xPosition = xPos;
            yPosition = yPos;
            color = ballColor;
            diameter = ballDiameter;
            groundPosition = groundPos;
            canvas = drawingCanvas;
         * Draw this ball at its current position onto the canvas.
        public void draw()
            canvas.setForegroundColor(color);
            canvas.fillCircle(xPosition, yPosition, diameter);
         * Erase this ball at its current position.
        public void erase()
            canvas.eraseCircle(xPosition, yPosition, diameter);
         * Move this ball according to its position and speed and redraw.
        public void move()
            // remove from canvas at the current position
            erase();
            // compute new position
            ySpeed += gravity;
            yPosition += ySpeed;
            xPosition +=2;
            // check if it has hit the ground
            if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
                yPosition = (int)(groundPosition - diameter);
                ySpeed = -ySpeed + ballDegradation;
            // draw again at new position
            draw();
         * return the horizontal position of this ball
        public int getXPosition()
            return xPosition;
         * return the vertical position of this ball
        public int getYPosition()
            return yPosition;
    }

    I'm not reading all of that. what do you see? here, try this out.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    public class BallRoom extends Applet implements Runnable, MouseListener, ActionListener {
         Thread thread;
         Rectangle border;
         Ball[] theBalls;
         int numberOfBalls = 10;
         Image bufferedScreen;
         Graphics2D bufferedG;
         double xSpeed=3.0, ySpeed=0.0;
         double gravity=1.2;
         int bounds=600;
         int speed=50;
         Button fastBut=new Button("Faster"), slowBut=new Button("Slower");
         Panel controlPanel = new Panel();
         public void init() {
              fastBut.addActionListener(this);
              slowBut.addActionListener(this);
              controlPanel.setLayout(new GridLayout(1,2));
              controlPanel.add(fastBut);
              controlPanel.add(slowBut);
              this.add(controlPanel);
              addMouseListener(this);
              theBalls = new Ball[numberOfBalls];
              setSize(bounds,bounds);
              border = new Rectangle(0,0,getSize().width,getSize().height);
              setBackground(Color.white);
              for(int a=0;a<numberOfBalls;a++){
                   theBalls[a]=new Ball(Math.random()*bounds,Math.random()*bounds,Math.random()*40+5,new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)),border,gravity);
         public void start() {
              thread = new Thread(this);
              thread.start();
         public void run() {
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              for(int a=0;a<numberOfBalls;a++){
                   theBalls[a].moveIt((int)(10-Math.random()*20),(int)(10-Math.random()*20));
              while(true){
                   for(int a=0;a<numberOfBalls;a++){
                        theBalls[a].moveIt();
                        for(int b=a+1;b<numberOfBalls;b++){
                             if(theBalls[a].intersects(theBalls)){
                                  swapSpeeds(theBalls[a],theBalls[b]);
                   repaint();
                   try{
                        thread.sleep(speed);
                   }catch(InterruptedException ex){
         public void swapSpeeds(Ball one, Ball two){
              double xVone=one.getxV();
              double yVone=one.getyV();
              double xVtwo=two.getxV();
              double yVtwo=two.getyV();
              one.setSpeeds(xVtwo,yVtwo);
              two.setSpeeds(xVone,yVone);
                   one.moveIt();
                   two.moveIt();
         public void paint(Graphics g) {
              g.setColor(Color.black);
              for(int a=0;a<numberOfBalls;a++){
                   theBalls[a].drawBall(g);
              Point2D.Double pointa=theBalls[0].getCenter();
              Point2D.Double pointb=theBalls[1].getCenter();
              double distance = pointa.distance(pointb);
              double deltaX = pointa.getX()-pointb.getX();
              double xSpot=theBalls[2].getX();
              double ySpot=theBalls[2].getY();
              g.drawString("X :"+String.valueOf(xSpot),20,20);
              g.drawString("Y :"+String.valueOf(ySpot),20,30);
              g.drawString("speed :"+String.valueOf(speed),20,40);
         public void update(Graphics g) {
              if(bufferedScreen==null){
                   bufferedScreen=createImage(getSize().width,getSize().height);
              bufferedG=(Graphics2D)(bufferedScreen.getGraphics());
              bufferedG.setColor(getBackground());
              bufferedG.fillRect(0,0,getSize().width,getSize().height);
              paint(bufferedG);
              g.drawImage(bufferedScreen,0,0,this);
    public void actionPerformed(ActionEvent e) {
              java.awt.Toolkit.getDefaultToolkit().beep();
              Button source = (Button)e.getSource();
              if(source==fastBut){
                   speed=speed-5;
                   if(speed<0){speed=0;}
              if(source==slowBut){
                   speed=speed+5;
         public void mousePressed(MouseEvent m){
              for (int a=0;a<numberOfBalls;a++){
                   if (theBalls[a].contains(m.getPoint())){
                        theBalls[a].setSpeeds( (5-(int)(Math.random()*10)),(int)(-40*(Math.random())) );
         public void mouseEntered(MouseEvent m){mousePressed(m);}
         public void mouseReleased(MouseEvent m){mousePressed(m);}
         public void mouseClicked(MouseEvent m){}
         public void mouseExited(MouseEvent m){}
    and this..
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class Ball extends Rectangle2D.Double {
         double a;                              //acceleration
         double yV=0, yVi=0, xV=0, xVi=0;     //velocity and initial velocity
         double t=1;                                       //time
         double roomWidth, roomHeight;
         double x_pos, y_pos;
         double ballDiam;
         double spring=.9;
         Rectangle room;
         Color color;
         Point2D.Double center;
         Ball(double x, double y, double diameter, Color color, Rectangle walls, double gravity) {
              a=gravity;
              room=walls;
              roomWidth=room.getSize().width;
              roomHeight=room.getSize().height;
              ballDiam=diameter;
              x_pos=x;
              y_pos=y;
              setRect(x,y,ballDiam,ballDiam);
              this.color=color;
              center = new Point2D.Double(x,y);
         public void moveIt() {
              setRect(xMove(),yMove(),ballDiam,ballDiam);
         public void moveIt(double x, double y) {
              setRect(xMove(x),yMove(y),ballDiam,ballDiam);
         public double xMove(double currentSpeed) {
              x_pos=getX();
              xV=currentSpeed;
              x_pos=x_pos+xV*t;
              return x_pos;
         public double xMove() {
              x_pos=getX();
              x_pos=x_pos+xV*t;
              if((x_pos<0) & ( xV<0  ) | ((x_pos>(roomWidth-ballDiam)) & ( xV>0  ))){
                   xV*= (-spring);
              return x_pos;
         public double yMove(double currentSpeed) {
              y_pos=getY();
              yVi=currentSpeed;
              yV=yVi+a*t;
              y_pos=y_pos+yV*t+.5*a*t*t;
              return y_pos;
         public double yMove() {
              double grav=a;
              if((y_pos>(roomHeight-(ballDiam+1)))|(y_pos<0)){ //negates gravity during impact
                   a=0;
                   if (y_pos<1 & y_pos>-.6){
                        yV=0;
              y_pos=getY();
              yVi=yV;
              yV=yVi+a*t;
              y_pos=y_pos+yV*t+.5*a*t*t;
              if((y_pos>(roomHeight-ballDiam)) & ( yV>0  )){
                   y_pos=roomHeight-ballDiam;
                   yV*= (-spring);
              if (y_pos<0 &  yV<0){
                   yV*= (-spring);
              a=grav;
              return y_pos;
         public void drawBall(Graphics g) {
              g.setColor(color);
              g.fillOval((int)getX(),(int)getY(),(int)ballDiam,(int)ballDiam);
              g.setColor(Color.black);
              g.drawOval((int)getX(),(int)getY(),(int)ballDiam,(int)ballDiam);
              g.drawString(String.valueOf(yV),(int)x_pos,(int)y_pos);
         public Point2D.Double getCenter(){
              center.setLocation(x_pos+.5*ballDiam,y_pos+.5*ballDiam);
              return center;
         public double getxV(){
              return xV;
         public double getyV() {
              return yV;
         public void setSpeeds(double x,double y){
              xV=x;
              yV=y;

  • How to move a button in gird layout(16-block game)?

    I am designing a 16-block puzzel game and don't have any idea about how to move buttons in a grid on mouse click.

    This is the code now me help me to solve this problem.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Puzzel extends JFrame {
              JButton[] arr = new JButton[15];
              String[] add = {"1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg","10.jpg","11.jpg","12.jpg","13.jpg","14.jpg","15.jpg"};
              int X;
              int Y;
              public Puzzel(){
                        Image image;
                        Toolkit toolkit= Toolkit.getDefaultToolkit();
                        image=toolkit.getImage("icon.jpg");
                        ImageIcon icon=new ImageIcon("icon.jpg");
                        setIconImage(image);
                        setTitle("Puzzal");
                        JMenuItem pic = new JMenuItem("Solved");
                        pic.setMnemonic('a');
                        JPanel jp = new JPanel(new GridLayout(4,4));
                        ArrayList list = new ArrayList();
    MouseListenerClass M1 = new MouseListenerClass();
                           for(int x = 0; x < arr.length; x++)
                               arr[x] = new JButton(add[x], new ImageIcon(add[x]));
                               getContentPane().add(arr[x]);
                              list.add(arr[x]);
                        Collections.shuffle(list);
                        for(int x = 0; x < list.size(); x++)
                              jp.add((JButton)list.get(x));
                            getContentPane().add(jp);
                                 pack();
                                 setSize(427,427);
                                        setResizable(false);
                        /*for(int x=0;x<arr.length;x++){
                             arr[x].addSelectionListener(new SelectionAdapter());
                   public void widgetSelected(SelectionEvent event){System.out.println("IN");
                        if (event.getSource().getClass().equals(Button.class)){
                             Button button = (Button) event.getSource();
                             if (button.getText().equals("") )
                                  Toolkit.getDefaultToolkit().beep();
                                  else
                                       this.swapPlaces(((Integer) button.getData()).intValue());
                   public void widgetDefaultSelected(SelectionEvent event){
                                  System.out.println("Widget was defaultselected: " + event.getSource());
               for(int x = 0; x < arr.length; x++)
              arr[x].addMouseMotionListener(M1);
              private class MouseListenerClass extends MouseMotionAdapter
                   public void mouseDragged(MouseEvent E)
                   X=E.getX();
                   Y=E.getY();
                   for(int x = 0; x < arr.length; x++)
                        arr[x].setBounds(X,Y,100,100);
    public static void main(String[] args){
                    new Puzzel().setVisible(true);}
         }

Maybe you are looking for

  • What Exactly is Happening in this Program???

    Hello All, Here is a Program, package myDemo; public class MyOverRidingDemo {      public MyOverRidingDemo() {           super();           // TODO Auto-generated constructor stub           A obj=new B();           obj.add();           System.out.pri

  • Is it possible to migrate just a few programmes over to my new iMac from G4

    I have just bought a new iMac 17" and I love it. I want to transfer only a few files over from my G4 iMac. Basically the songs from iTunes, photos from iPhoto and one game and maybe MS Office. I'm planning on using the Migration assistant but I don't

  • I cant upload a movie from a DVD???

    i have recorded a movie i made on a blank DVD. i was told i could insert the DVD and import and edit it if i needed. i was told the computer would notice a difference between a Copyrighted DVD (ex: a movie like Titanic) and a home made DVD (like a pr

  • Much difference in speed? G5 vs Intel

    I wonder if I've been greedy.. I have an iMac 20" 2Ghz G5 ( 1.5gb RAM ) - I've just ordered a 24" 2.33Ghz Intel Core 2 Duo ( 2gb RAM ). And I'm starting to worry that I've been a tad silly! Is there much of a speed difference between these two set-up

  • How Can I Create A Contact Form In Dreamweaver Using ASP

    I tried to create a contact form using php, but that failed epically. The server doesn't support php, and there isn't anything I can do about that. My only option now is to create it using ASP but I can't find a good tutorial on how to do so. Please