[b]Using audioclips in JFrame[/b]

hey!!!!!!
i want to know how to use audio clips in a jframe.
i know how to use in the applet.
plese help me with steps.

In the future Swing related questions should be posted on the Swing forum.
Read the tutorial on [url http://java.sun.com/docs/books/tutorial/]Sound. It highlights the differences between an applet and application.

Similar Messages

  • Intialized a AudioClip In JFrame(help pls)

    alarmSound = getAudioClip(getDocumentBase(),"alarm.au")
    ^
    .\Winpro.java:24: cannot resolve symbol
    symbol : class alarmSound
    location: class Winpro
    alarmSound = getAudioClip(getDocumentBase(),"alarm.au")
    ^
    2 errors
    what the problem for the error above..I wana to initial the audio inside the application(Jframe)
    i use
    AudioClip alarmSound ;
    alarmSound = getAudioClip(getDocumentBase(),"alarm.au");
    It doesnt; seeem to work

    Hi,
    You must learn about the Sound API first...
    JRG

  • Using JPanel with JFrame

    I am using a JFrame to encapsulate my program. I want to have a JPanel inside my JFrame to handle all of my 2d displaying (like fillRect() etc...). I used forte to set this up but I am having problems dispaying on the JPanel. Here is my code:
    here is how I call the function from the main .java file
    I dubuged this and know it works (proof will come later)
    private void Start_ButtonActionPerformed(java.awt.event.ActionEvent evt)
    myDisplay.draw();
    here is my entire JPanel class
    import java.awt.*;
    import javax.swing.*;
    public class Display extends javax.swing.JPanel
    public Display() {
    initComponents();
    public void paintComponent(Graphics g )
    System.out.println("1");
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillOval(50,10,60,60);
    public void draw()
    System.out.println("1");
    this.repaint(); //i also tried repaint() but it didn't work either
    System.out.println("2");
    private void initComponents()
    setLayout(new java.awt.BorderLayout());
    when I press the start button, 1 and 2 are displayed but 3 isn't. For some reason the repaint() function is not telling the paintComponent function to work. Any help is appreciated.
    Thanks,
    Every_man

    Every_man,
    After doing the super.paintComponent(g); you must use Graphics2D. So you next line should cast your graphics object to a graphics 2D object, like this. Graphics2D g2 = (Graphics2D)g;

  • Using getContentPane() in JFrame class

    Hello,
    I'm reading Bruce Eckel's book.
    In chaapter 14, I read TextArea.java.
    My question is:
    What is the purpose of getContentPane() in the constructor TextArea() in the code below ?
    Isn't JFrame IS a Container ? why bother to get another Container ?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import com.bruceeckel.swing.*;
    import com.bruceeckel.util.*;
    public class TextArea extends JFrame {
    private JButton
    b = new JButton("Add Data"),
    c = new JButton("Clear Data");
    private JTextArea t = new JTextArea(20, 40);
    private Map m = new HashMap();
    public TextArea() {
    // Use up all the data:
    Collections2.fill(m, Collections2.geography,
    CountryCapitals.pairs.length);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Iterator it = m.entrySet().iterator();
    while(it.hasNext()) {
    Map.Entry me = (Map.Entry)(it.next());
    t.append(me.getKey() + ": "+ me.getValue()+"\n");
    c.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    t.setText("");
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(new JScrollPane(t));
    cp.add(b);
    cp.add(c);
    public static void main(String[] args) {
    Consoleb.run(new TextArea(), 475, 425);
    }

    I appreciate the reply.
    There are endless API to read.
    I found this:
    For conveniance JFrame, JDialog, JWindow, JApplet and
    JInternalFrame, by default, forward, by default, all
    calls to the add, remove and setLayout methods, to
    the contentPane. This means you can call:
    rootPaneContainer.add(component);That was introduced in 1.5. May people still use older versions of Java, so use that add method with caution. I myself see no reason to use it, since it is a bit of a hack.
    Another question on the side:
    How can I remove a topic that I created ?Like karma, no thread ever goes away :-)

  • Security Access Violation while using AudioClip

    'Sounds[6]= Applet.newAudioClip(new URL("file:audio/itemsprout.wav"));'
    When I try and run the applet on a browser, I get a access violation error. I'm pretty sure it's the URL part, but how do I bypass it? Or go around it?
    Thanks in advance,
    Adrian Kwok

    Argh.. But it doesn't convert mid files.. >_<its not supprted with Applet.AudioClip either so don't worry 'bout d'at -
    though if you wish to venture into the javax.sound.sampled API (never used it - but I do know its there) midi is supported

  • Using Paint in JFrame

    I am trying to divide a frame into a number of different rectangles, and for some reason I can't get the paintComponent to work. Help!!

    I was wrong in reply one. The paint method in JFrame shows up in the Container methods section, so JFrame uses paint as a Container.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PaintingDemo extends JPanel {
      int
        width,
        height;
      int[][] circles = {
        {2,20}, {100,50}, {180,200}, {90,150}
      int[][] squares = {
        {40,90}, {100,200}, {150,300}
      int[][] rectangles = {
        {100,100}, {200,100}, {300,300}
      public PaintingDemo(int width, int height) {
        this.width = width;
        this.height = height;
        setBackground(Color.pink);
        setPreferredSize(new Dimension(width, height));
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(Color.blue);
        int x,y;
        for(int i = 0; i < circles.length; i++) {
          x = circles[0];
    y = circles[i][1];
    g2.fill(new Ellipse2D.Double(x, y, 20, 20));
    g2.setPaint(Color.red);
    for(int i = 0; i < squares.length; i++)
    g2.fill(new Rectangle2D.Double(squares[i][0], squares[i][1], 10, 10));
    g2.setPaint(Color.orange);
    for(int i = 0; i < rectangles.length; i++)
    g2.fill(new Rectangle2D.Double(rectangles[i][0], rectangles[i][1], 50, 25));
    public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new PaintingDemo(400,400));
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • How to use Rightclick with JFrame

    Hello,
    I got a minesweeper game that using the JFrame extend Actionlistener
    i used the Jbutton a minefileds and used the Actionperformed to obtain filed number when press the button.
    the problem is within the rightclick mouse , icoludn't use it to get the button numbe whuch is the field
    I tried to add JFrame extend Actionlistener,MouseListener // but if faild.
    public class MListener extends MouseAdapter{     //also got problem in getting the button number????what is the solution
    Regards

    The MouseEvent contains the Component that you clicked on. So you just cast the Component to a button.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    And we don't want to see you entire application. Create a JFrame with a single button and add the ActionListener and the MouseListener to the button to demonstrate your problem.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Using AudioClips in a Frame

    Hi, when I run my porgram through the main, the AudioClips do not work and they are vital to my program. Does anyone know how to fix this?

    That works, but playing it doesn't
    AudioClip test=getAudioClip(getDocumentBase(), "test.au");
    test.play();There is the right code but it doesn't play the sound...

  • Using tab in JFrame

    I have an app with a JFrame and a few different JPanels in it. There are only a few different texboxes that you can put information into and i want to know is there anyway to set up the Tab order so that it will only go to them.
    Also when you tab to a textbox, how do you set it so that the contents of the box are selected/highlighted? you know so that when you type something new the old contents are overwritten
    thanks

    Thanks for putting me in the write direction, but i can't get it working just how i'd like it. I have a key listener in there that selects the contents of the Texbox if "TAB" is pressed. But i cant get the focus listener to work. i'd like it to select all if selected by mouse aswell.
    Here is my code, it's just a class of JTextbox that will only accept numbers.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class NumberField extends JTextField implements FocusListener {
      public class NumberFilterDocument extends PlainDocument {
        private StringBuffer __scratchBuffer;
        public NumberFilterDocument() {
          __scratchBuffer = new StringBuffer();
        public void insertString(int offset, String text, AttributeSet aset)
          throws BadLocationException
          if(text == null)
            return;
          __scratchBuffer.setLength(0);
          // Reject all strings that cause the contents of the field not
          // to be a valid number (i.e., string representation of a double)
          try {
            __scratchBuffer.append(getText(0, getLength()));
            __scratchBuffer.insert(offset, text);
            // Kludge: Append a 0 so that leading decimal points
            // and signs will be accepted
            __scratchBuffer.append('0');
          } catch(BadLocationException ble) {
            ble.printStackTrace();
            return;
          } catch(StringIndexOutOfBoundsException sioobe) {
            sioobe.printStackTrace();
            return;
          try {
            Double.parseDouble(__scratchBuffer.toString());
          } catch(NumberFormatException nfe) {
            // Resulting string will not be number, so reject it
            return;
          super.insertString(offset, text, aset);
    public NumberField(int columns) {
        super(columns);
        setDocument(new NumberFilterDocument());
    protected void processKeyEvent(KeyEvent ke){
              if( ke.getKeyCode() == KeyEvent.VK_TAB){
              this.selectAll();
               super.processKeyEvent( ke);
    public void focusGained(FocusEvent fe) {
                this.selectAll();
    public void focusLost(FocusEvent fe) {}
    }

  • Sound in a jFrame

    Hi, just want to ask if anyone has any code samples to play files using a jFrame (not an applet) using the javax.sound.sampled package. All I am trying to do is play a sound file that is already defined in the code when I press a button. All I can find are complex programs and 2 page long explanation documents.
    Any help would be kindly appreciated.

    Does it have to be that special package, or would
    anything that works help like using AudioClip?
        String clipname = "sound.wav";
    try {
    URL clipUrl = new URL("file:" + clipname);
    AudioClip audioClip =
    Applet.newAudioClip(clipUrl);
    audioClip.play();
    Thread.currentThread().sleep(3000);
    } catch (Exception e) {
    e.printStackTrace();
    hey, String clipname = "sound.wav"; goes in the atributes declaration? or it goes later than the constructor of the class? where it goes?, sorry for questionate a lot, Im trying to learning

  • Jukebox Application and AudioClip

    For my final project in a Java course we were instructed to create a "java jukebox." We were given a few boundaries but we were free to choose a direction as long as it had a play, and a stop button, and as long as it actually played music. I got the layout where I wanted it, but when I began to write the musical portion I ran in to several brick walls. I started to try and use MP3 for my source, but quickly moved beyond the scope of the course. I found MIDI versions of the songs I wanted to play, and decided to use those. Doing some reading on the internet, I saw that AudioClip was the preferred solution. However, every different way I try to declare an AudioClip I run into problems.
    This is my full program, with my latest efforts to play an AudioClip commented for emphasis. I have not included Exception catching because we have not covered it, and I do not have any understanding of them yet.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.net.URL;
    public class Music extends JFrame implements ActionListener
         int userPick = 0;
         //URL url1 = new URL("file:/music/song0.mid");
         //AudioClip mSong0 = JApplet.newAudioClip (url1);
         ImageIcon iPlay = new ImageIcon("./images/play.png");
         ImageIcon selPlay = new ImageIcon("./images/playSel.png");
         JButton sPlay = new JButton (iPlay);
         ImageIcon iStop = new ImageIcon("./images/stop.png");
         ImageIcon selStop = new ImageIcon("./images/stopSel.png");
         JButton sStop = new JButton (iStop);
         String[] songs = {"Song 0", "Song 1", "Song 2"};
         JComboBox sBox = new JComboBox(songs);
         JLabel titleLabel = new JLabel("Caffeinated Tunes", JLabel.CENTER);
         ImageIcon jukeBox = new ImageIcon("./images/jukebox.jpg");
         JLabel jukeLabel = new JLabel(jukeBox);
         JLabel songLabel = new JLabel(" ", JLabel.CENTER);
         JLabel artistLabel = new JLabel(" ", JLabel.CENTER);
         ImageIcon cdArt = new ImageIcon("./images/blank.png");
         JLabel cdLabel = new JLabel(cdArt);
         ImageIcon song0 = new ImageIcon("./images/Song0.jpg");
         JLabel songLabel0 = new JLabel(song0);
         ImageIcon song1 = new ImageIcon("./images/Song1.jpg");
         JLabel songLabel1 = new JLabel(song1);
         ImageIcon song2 = new ImageIcon("./images/Song2.jpg");
         JLabel songLabel2 = new JLabel(song2);
         JLabel blank = new JLabel("        ", JLabel.CENTER);
         public Music()
              Container contentPane = getContentPane();
              contentPane.setLayout(new BorderLayout(2,2));
              JPanel pNorth = new JPanel();
                   pNorth.setBackground(Color.black);
                   pNorth.setLayout(new BorderLayout(0,0));
                   pNorth.add(BorderLayout.NORTH, jukeLabel);
                   pNorth.add(BorderLayout.CENTER, titleLabel);
                   titleLabel.setOpaque(false);
                   titleLabel.setForeground(Color.white);
              JPanel pCenter = new JPanel();
                   pCenter.setBackground(Color.black);
                   pCenter.add(sPlay);
                   pCenter.add(sStop);
                   pCenter.add(sBox);
                   ButtonGroup songManip = new ButtonGroup();
                   songManip.add(sPlay);
                   songManip.add(sStop);
                   sPlay.setBackground(Color.black);
                   sPlay.setBorderPainted(false);
                   sPlay.addActionListener(this);
                   sStop.setBackground(Color.black);
                   sStop.setBorderPainted(false);
              JPanel pSouth = new JPanel();
                   pSouth.setBackground(Color.black);
                   pSouth.setLayout(new BorderLayout(0,0));
                   pSouth.add(BorderLayout.NORTH, artistLabel);
                   pSouth.add(BorderLayout.CENTER, songLabel);
                   JPanel cdCover = new JPanel();
                        cdCover.setBackground(Color.black);
                        cdCover.setLayout(new BorderLayout(0,0));
                        cdCover.add(BorderLayout.CENTER, cdLabel);
                        cdCover.add(BorderLayout.SOUTH, blank);
                   pSouth.add(BorderLayout.SOUTH, cdCover);
                   songLabel.setOpaque(false);
                   songLabel.setForeground(Color.white);
                   artistLabel.setOpaque(false);
                   artistLabel.setForeground(Color.white);
              contentPane.add(BorderLayout.NORTH, pNorth);
              contentPane.add(BorderLayout.CENTER, pCenter);
              contentPane.add(BorderLayout.SOUTH, pSouth);
         public static void main(String[] args) throws Exception
              JFrame jBox = new Music();
              jBox.setTitle("Music, made on Coffee Cups");
              jBox.setSize(360, 705);
              jBox.setResizable(false);
              jBox.setLocationRelativeTo(null);
              jBox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jBox.setVisible(true);
         public void actionPerformed(ActionEvent Py)
              userPick = sBox.getSelectedIndex();
              if (userPick == 0) {
                   songLabel.setText("Song 0");
                   artistLabel.setText("Artist 0");
                   cdLabel.setIcon(song0);
                   //mSong0.play();
              if (userPick == 1) {
                   songLabel.setText("Song 1");
                   artistLabel.setText("Artist 1");
                   cdLabel.setIcon(song1);
              if (userPick == 2) {
                   songLabel.setText("Song 2");
                   artistLabel.setText("Artist 2");
                   cdLabel.setIcon(song2);
    }With this example, it fails to compile with an error. It errors out with a MalformedURLException, which I understand to mean that the URL source has been typed incorrectly. I have the code in a folder, with the music I want to use in a sub folder. I tried to place the music in the same folder and changed my URL to the following.
         //URL url1 = new URL("file:song0.mid");
            //AudioClip mSong0 = JApplet.newAudioClip (url1);I am developing this on a Windows Vista Enterprise machine with JDK6 installed. I use Textpad 5.1.0 to create my .java and compile my .class files. If I can just get one MIDI to work and play, I believe the rest will follow smoothly.
    Thanks in advance for any help

    Arcanum wrote:
    I'm pretty sure that AudioClip is only supposed to play .AU files, and that MIDI files don't work with it. However, there are classes in javax.sound.midi that may allow it to play those files.
    EDIT: [The Java Sound Demo|http://java.sun.com/products/java-media/sound/samples/JavaSoundDemo/] has source code and shows how to play MIDI's
    EDIT: The AudioClip class does indeed only support .AU files. See the Java Tutorial [section on sounds in applets|http://java.sun.com/docs/books/tutorial/deployment/applet/sound.html].
    The code I posted previously plays a midi file on my computer using AudioClip. It is not an applet, although it uses both Applet and AudioClip methods.
    Posssibly you are experiencing unrelated problems, or misunderstood something.

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

  • How to change Font Type of the Title Text of a JFrame?

    Hi,
    I want to set a different Font Type for the Title text of the titlebar of my JFrame.
    Is it possible? Can anyone show me how if it is?
    Thanks.
    Niteen

    Michael,
    Thanks. It works!
    But there was a problem. I was not using the :-
    JFrame.setDefaultLookAndFeelDecorated(true);
    so I have to use it now.
    Is it possible to do it without the default decorated look and feel? Because the default LNF title bar has too much height and I am cramped for space.
    I know that's no excuse. I tried but it doesn't work.. I am using a extended JFrame like this:-
    class Testing extends JFrame
    public Testing()
    setSize(300,100);
    setLocation(400,200);
    Container container = getContentPane();
    /* add components to this container here */
    setVisible(true);
    When I use getComponent() for the container, I get an ArrayIndexOutOfBound Exception.
    When I set the argument to getComponent(0), the font in the title bar is not changed.
    What else should I do?
    Thanks.
    Niteen.

  • Use of JDBC Trace feature

    I want to see what SQL statements are executed against HANA when I run BObj Analysis for Excel on top of HANA views I had created. Accordingly to the HANA Development Guide p.63 it should be possible. Actually, I don't see my SQL statements in the log.
    Details are as follows:
    1. I have enabled JDBC Trace in HANA Studio, in properties of the HANA db instance I'm working with. Well, the Guide advises to use a separate NGDBC.JAR for it, but I assumed that would be the same functionality. Q1: Is there any difference in terms of JDBC Trace contents, depending on the way it's been enabled with?
    2. I have an analytic view MYCONTENT.ANV_001 that has, say, attributes SHIPTO and CALMONTH and a measure SALES. When I open the view in BObj Analysis for Excel, I expect it to run a SQL statement like SELECT SALES FROM MYCONTENT.ANV_001
    3. Yet I don't see anything like that. The only SQL statement that may be related is "select * from DUMMY".
    4. I tried to navigate through the view in Analysis for Excel, e.g. do some drilldowns and filters, but it continued running the same SQL statement against HANA.
    Q2: Have I picked the executed SQL statement right? If yes, does it mean that BObj Analysis for Excel always generates most generic query against HANA? If no, how can I check what is the SQL statement being executed?
    Update 5. I tried to enable JDBC Trace using the NGDBC.JAR library, but see no trace logs appearing at all. Q3: Could it be something wrong with the trace settings (well, there are just 4 of them, and it would be hard to make a mistake)? Q4: Does Analysis for Excel use JDBC Driver at all to access HANA?
    Thanks!
    /RB
    Edited by: Roman Bukarev on Dec 13, 2011 4:53 AM
    Edited by: Roman Bukarev on Dec 13, 2011 4:54 AM

    I second that. Using JFrame instead of JApplet is easy once you've seen an example:
    http://java.sun.com/docs/books/tutorial/uiswing/learn/example1.html
    When learning Swing, I can think of only disadvantages to using JApplet over
    JFrame. Why do textbooks use applets? Old habits die hard and they
    are out-of-date in their view of Java.
    Side comment: when learning a new topic, like JDBC, I would
    strongly advice you to write the simplest possible code at first.
    In other words, skip the Swing and write simple console apps:
    1. select and dump the contents of a table.
    2. gradually do more sophisticated selects...
    3. insert a record into a table using some fixed values.
    3. delete records from a table.
    4. update records using some fixed values.
    Once you are comfortable doing CRUD, and used PreparedStatement!,
    then add a GUI. And if your code is well-written, the GUI and the back-end
    are separate enough anyway, that you can write and test them apart.

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

Maybe you are looking for