Validating JTextfield in an Applet

I am doing a simple assignment for a Java class I am taking. The assignment consists of doing the Tower of Hanoi with just symbols showing the moves of the disks. I have been successful in writing the recursive statement and init() but I am having trouble validating the JTextfield in the applet. I want to validate the entry is only between 1 and 9. Nothing else and no letters. Here is my code at the present time. If anyone could help I would appreciate it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HWProblem6_37Hanoi extends JApplet implements ActionListener
/** Initialization method that will be called after the applet is loaded
into the browser.*/
JLabel directions;
JTextField userInput;
//attach JTextArea to a JScrollPane so user can scroll results
JTextArea outputArea = new JTextArea(10, 30);
//Set up applet's GUI
public void init()
//obtain content pane and set its layout to FlowLayout
Container container=getContentPane();
container.setLayout( new FlowLayout() );
JScrollPane scroller = new JScrollPane(outputArea);
//create directions label and attach it to content pane
directions = new JLabel("Enter a Integer Between 1 and 9: ");
container.add( directions );
//create numberField and attach it to content pane
userInput = new JTextField(10);
container.add( userInput );
//register this applet as userInput ActionListener
userInput.addActionListener( this );
container.add (scroller);
public void actionPerformed(ActionEvent event)
//Initialize variables
int number = 0;
while (number == 0)
number = Integer.parseInt(userInput.getText());
if ((number<1) || (number >9))
userInput.setText(" ");
number =0;
showStatus("Error: Invalid Input");
else
showStatus("Valid Input");
tower(number,1,2,3);
public void tower(int n, int needle1/*source*/, int needle2/*destination*/, int needle3/*free space*/)
if (n >0)
tower(n-1, needle1, needle3, needle2);
outputArea.append(needle1 + " -> " + needle3 + "\n");
tower(n-1, needle2, needle1, needle3);
}

How to Use Formatted Text Fields
http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html

Similar Messages

  • Validating JTextField for Date Format

    hello,
    everybody.
    i am trying to perform a validation on text field, i.e if the input is in a date format then it will show, other wise it will consume the character.
    please help me out of this problem i am stucked with it.
    waitng for reply. the following is my code.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JTextField(5);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
         public void keyPressed(KeyEvent ke)
              DateFormat df;
              df = DateFormat.getDateInstance();
              df = (DateFormat) ke.getSource();
              if(!(df.equals(date)))
                   ke.consume();
         public void keyReleased(KeyEvent ke)
    }

    hi,
    thanks very much, u gave me great idea.
    according to ur suggestion i used JFormattedTextField as well as SimpleDateFormat, but while giving keyevent i am getting the error,
    so please if possible reply for this.
    the error is
    java.lang.ClassCastException
         at RilJDateField.keyTyped(RilJDateField.java:61)
         at java.awt.Component.processKeyEvent(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and my source code is
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JFormattedTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         SimpleDateFormat formatter;
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JFormattedTextField();
              text.setColumns(10);
              formatter = new SimpleDateFormat("dd mm yyyy");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
              Date date = (Date) ke.getSource();
              if(!(date.equals(formatter)))
                   ke.consume();
         public void keyPressed(KeyEvent ke)
         public void keyReleased(KeyEvent ke)
    }

  • Prompting the user to enter a valid value in an applet

    hi everyone!
    i have this code and i want to prompt the user to set a value<1000.
    this doesnt work.if i enter a value <1000 the input dialog appears again.
    whats wrong?
    public void init()
       String j = JOptionPane.showInputDialog(null, "Enter a number less than 1000 but greater than 0");
       int i = Integer.parseInt(j);
       while(i>1000||i<1)
          String k = JOptionPane.showInputDialog(null, "Enter a number less than 1000 but greater than 0");
          int y = Integer.parseInt(k);
    ....code executed while i<1000 or i>0

    Your while is looping on i, but inside you're setting
    y not i. This should work:
    do {
    String k = get input from option pane
    int i = Integer.parseInt(k);
    } while (i > 1000 || i < 1);
    In BinaryDigit's code, you won't have access to "i" after the loop. Declare it outside the loop (as you had it).
    int i = 0;
    do {
    String k = get input from option pane
    i = Integer.parseInt(k);
    } while (i > 1000 || i < 1);

  • Validating jtextfield has input

    Can someone kindly explain why this seemingly logical construction doesn't work?
    if(txtOperand1.getText()==null)
    JOptionPane.showMessageDialog(this,"nothing in op 1");
    I'm just trying to make a simple calculator that needs to know that something has been entered into the operand fields.
    Thanks!

    Perhaps your test looked like this:if(txtOperand1.getText()=="")? If so, then that would explain why it didn't work. To compare the contents of two String objects you must use their equals() method, like this:if(txtOperand1.getText().equals(""))PC&#178;

  • A Question of JTextField in applet(using plug-in 1.4)

    With java plug-in 1.4, when we add a JTextField in an applet, and use some Chinese input method to input some text, a "input window" will pop out to preview the word what you inputed. But after you refresh the page and input again, that "input window" dispearred, and we can find this exception in console:
    java.lang.NullPointerException
         at sun.awt.im.CompositionArea.setText(CompositionArea.java:163)
         at sun.awt.im.CompositionAreaHandler.inputMethodTextChanged(CompositionAreaHandler.java:183)
         at sun.awt.im.CompositionAreaHandler.processInputMethodEvent(CompositionAreaHandler.java:144)
         at sun.awt.im.InputMethodContext.dispatchEvent(InputMethodContext.java:175)
         at java.awt.Component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1437)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    How to solve this problem? or can I shut off the "input window" when use Chinese input method?

    As this class extends ArrayList the size() refers to the method in ArrayList. In ArrayList size() returns the size of the ArrayList funnily enough. See the API for ArrayList for more info.
    BTW I wouldn't have extended ArrayList but used an ArrayList attribute because I feel that the class TextFile fails the
    TextFile "is a" ArrayList
    test for inheritence.
    Richard

  • Starting an applet with the cursor in a JTextField

    I want the cursor to be flashing in a JTextField when an applet has started. I've tried textField.requestFocus ( ) and textField.grabFocus ( ) with no success. Using J2SDK ver 1.4. Please help!

    Add a ComponentListener to the applet and put the textField.requestFocus() call in the componentShown() method.

  • Help?...JTextField Validation...

    Hello Gurus...
    Here is the code...
    It is the Class for validating real numbers only...
    The problem which I have been facing is that, When I enter "." in the textfield at any other place like//
    [ 1st time I entered in this fashion] 2.365
    [>>
    now i wanna place a dot"." after 6...by deleteing the "." after 2 and inserting it after 6 [i.e;] 236.5
    <<]
    [I get the mesgbox which i have included in this class, saying no more decimals should be placed here]
    'coz only one time a decimal is placed in a real or double number...
    [ this is wrong... 2.36.6] ...[BUT] [ 2.698 is right]...But my class is ensuring that there is only one decimal... But when u just entered a dot and u wanna place it at another place this is cumbersome and I couldn't find a way how to het rid of this problem....plz help///
    import javax.swing.*;
    * Insert the type's description here.
    * Creation date: (7/15/2009 6:32:41 PM)
    * @author: jav
    public class TextFieldForReal extends javax.swing.text.PlainDocument{
    int maxSize;
    JTextField txtField = null;
    int dot = 0;
    * TextFieldFormatter constructor comment.
    public TextFieldForReal(int limit) {
    maxSize = limit;
    * TextFieldFormatter constructor comment.
    public TextFieldForReal(int limit, JTextField txtObj) {
    maxSize = limit;
    this.txtField = txtObj;
    public void insertString(int offs, String str, javax.swing.text.AttributeSet a)
    throws javax.swing.text.BadLocationException {
    if ((getLength() + str.length()) <= maxSize) {
    if (str == null) {
    return;
    char[] upper = str.toCharArray();
    String buffer = "";
    for (int i = 0; i < upper.length; i++) {
    if (Character.isDigit(upper)){
         buffer += upper[i];
    else if( upper[i] == '.'){
              dot++;
              if(dot == 1)
              buffer += upper[i];
              else{
              JOptionPane.showMessageDialog(null, "No more decimal can placed here");
              break;
    if (!Character.isDigit(upper[i]) && upper[i] != '.') {
    JOptionPane.showMessageDialog(null, "Invalid Input");
    txtField.requestFocus();
    break;
    super.insertString(offs, buffer, a);
    } else {
    throw new javax.swing.text.BadLocationException(
    "Insertion exceeds max size of document", offs);
    /*****USAGE of the above class for validation*****/
    JTextField tf = new JTextField();
    TextFieldForReal textFieldForReal = new TextFieldForReal (10, tf);
    tf.setDocument(textFieldForReal);
    Help,
    jav

    you could check if text in your JTextField matcehs
    some regex, for example
    String text = myJTextField.getText();
    boolean isLegalNumber = text.matches("\\d+\\.?\\d*");this code checks if text consists of one or more
    digits, then optionally a dot, and then none or more
    digits again.
    HTHSorry, I didn't tell u that I've to do it with JDK 1.2 ...
    So regex is not included in JDK1.2

  • Entering data in an HTML with an Applet?

    I have a small application I made with Swing. now, I want to make it html for use with Explorer. and I have 2 challanges:
    1. How do I get use input in an Applet? (the example in the tutial only applies to showing text.
    2. How do I access the database with JDBC?
    Thanks, Benny.

    question 1 is:
    Can I use TextField or JTextField in an Applet to
    receive input from the user.Since an Applet is a Container... what do you think? And why didn'T you simply try or read the API? Or the Swing tutorial?
    Question 2:
    I only know about Applets. What I need to do is
    receive input from the user (e.g. first & last name,
    e-mail and phone number) and update the data into the
    database (currently MDB and MySQL in the near
    future).
    I know how to do this with swing and
    JDBC localy. but, how do I do it when my GUI
    is HTML / webpage?Signed applet and high hopes that nobody's using the packets sent by your applet to hack and wreck your DB.

  • Forms9i- Why base on applet?

    Hi every body,
    Why Forms 9i base on applet? Any one know applet is very slow, could migrate fastly from application developed with Forms9i to application developed with J2EE?
    Thanks in advanced,

    Nguyen,
    its too easy to say that Applets are slow and J2EE is fast without having to prove it.
    In fact there are two compelling arguments for Applets to be used with Forms:
    1. Forms applications support high transaction volumes and users are used to type fast and have multi row updates and scrolling. I agree that HTML based applications improved with teh advent of Struts and Java Server Faces - or UIX in Oracle JDeveloper, but this doesn't really allow the same loevel of type ahead and immediate validation as a Java Applet can do. I am certain that to some extend the J2EE worls will get there too, but this is not yet the case. So umless you are willing to change the navigation and transaction handling model, using J2EE over Java Applets in Forms is a step back in functionality and productivity.
    2. The Forms architecture always separated the interface rendering from the business logic, using Microsoft Foundation classes on Windows and Motif on UNIX. This gave us teh great opportunity to move all our customer investments in Forms to the Web by coming up with a generic set of Java classes to build Applets. Don't knwo how big your Forms application is, but if it has more that several hundreds of modules and assuming it is business critical, you would love us for that.
    Don't be ignorant and measure the startup time as speed. If you are on a sound network and Forms is up and running, you wont see a difference to Forms running on client-server.
    There are Oracle partners working on a migration from Forms to J2EE and you can read about their doing on teh Forms Web page here on OTN.
    Frank

  • APPLETS PLEASE HELP !!!!!!

    Does anyone know how to close an applet dynamically from within its own code.
    Have tried via javascript but the applet I created using the object tag fails to communicate correctly. Says 'Object does not support this operation'.
    If anyone can help I would be grateful as this is a major issue now.
    Thanks Andrew Mercer

    Thankyou very much for your help.
    I can now use java code from an applet to close the window that surrounds this applet.
    However I still have one problem that I cannot solve by looking through the documentation.
    My applet basically is used to copy files from server to client cache. Once each file is fully copied over then the applet has done its job and can be closed.
    The main Browser window stays open all this time and each applet window is opened and file transfered by hitting a link on this window from a list of links that can run into 100's.
    The first time this operation is requested the JSObject.getWindow(this) call returns a valid reference to the applet within the window.
    Once the first window is closed the next JSOBject.getWindow(this) fails, in fact it goes no further and does not return an exception or suitable message.
    This happens even if I have closed the window manually.
    How can I use the getWindow(this) call for subsequent windows?
    Depending where I put the getWindow(this) I can actually make the applet init operation stall and go no further.
    Thanks again.
    Andrew Mercer

  • Cut and paste problem in an applet :(

    Hi All,
    I have developed an applet based GUI and now I wanted to cut and paste some text from an external application say from a notepad(Windows) to a
    JTextfield in the applet. I tried to do it on a applet but it was not allowing me to do it. I was able to do the same(cut and paste) on a textfield when run as an application. So does the cut and paste operation has anything to do with the sandbox security provided by an applet model?. This sounds bit crazy or maybe Im missing something here. Would appreciate help on this.
    Thanks a ton!
    Thanks,
    Ram

    You can always use CTRL-C and CTRL-V to copy/paste, but if you want to right-click, you have to implement it yourself.. Here's MY implementation, if even has 'Undo'!
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class CTPopupMenuMouseListener extends MouseAdapter
           private JPopupMenu popup = new JPopupMenu();
           private JMenuItem undoItem, cutItem, copyItem, pasteItem, deleteItem, selectAllItem;
           private JTextComponent textComponent;
           String savedstring="";
           String lastactionselected="";
           public CTPopupMenuMouseListener()
                  Action action = new AbstractAction("Undo")
                    public void actionPerformed(ActionEvent ae) {
                         if(lastactionselected.compareTo("")!=0){
                             textComponent.setText("");
                             textComponent.replaceSelection(savedstring);
                  undoItem = popup.add(action);
                  undoItem.setMnemonic('t');
                  popup.addSeparator();
                  action = new AbstractAction("Cut")
                    public void actionPerformed(ActionEvent ae) {
                          lastactionselected="c";
                          savedstring=textComponent.getText();
                          textComponent.cut();
                  cutItem = popup.add(action);
                  cutItem.setMnemonic('t');
                  action = new AbstractAction("Copy")
                    public void actionPerformed(ActionEvent ae) {
                          lastactionselected="";
                          textComponent.copy();
                  copyItem = popup.add(action);
                  copyItem.setMnemonic('c');
                  action = new AbstractAction("Paste")
                    public void actionPerformed(ActionEvent ae) {
                          lastactionselected="p";
                          savedstring=textComponent.getText();
                          System.out.println("in paste code savedstring is: "+savedstring);
                          textComponent.paste();
                  pasteItem = popup.add(action);
                  pasteItem.setMnemonic('p');
                  action = new AbstractAction("Delete")
                    public void actionPerformed(ActionEvent ae) {
                          lastactionselected="d";
                          savedstring=textComponent.getText();
                          textComponent.replaceSelection("");
                  deleteItem = popup.add(action);
                  deleteItem.setMnemonic('d');
                  popup.addSeparator();
                  action = new AbstractAction("Select All")
                     public void actionPerformed(ActionEvent ae) {
                          lastactionselected="s";
                          savedstring=textComponent.getText();
                          textComponent.selectAll();
                  selectAllItem = popup.add(action);
                  selectAllItem.setMnemonic('a');
            public void mouseClicked(MouseEvent e)
                  if (e.getModifiers()==InputEvent.BUTTON3_MASK)
                         if (!(e.getSource() instanceof JTextComponent))
                               return;
                         textComponent = (JTextComponent)e.getSource();
                         textComponent.requestFocus();
                         boolean enabled = textComponent.isEnabled();
                         boolean editable = textComponent.isEditable();
                         boolean nonempty = !(textComponent.getText()==null || textComponent.getText().equals(""));
                         boolean marked = textComponent.getSelectedText()!=null;
                         boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null)
                                    .isDataFlavorSupported(DataFlavor.stringFlavor);
                         undoItem.setEnabled(enabled && editable);
                         cutItem.setEnabled(enabled && editable && marked);
                         copyItem.setEnabled(enabled && marked);
                         pasteItem.setEnabled(enabled && editable && pasteAvailable);
                         deleteItem.setEnabled(enabled && editable && marked);
                         selectAllItem.setEnabled(enabled && nonempty);
                        int nx=e.getX();
                        if (nx>500)
                            nx=nx-popup.getSize().width;
                         popup.show(e.getComponent(),nx, e.getY()-popup.getSize().height);
                  }else if ( e.getClickCount()==2 )
                        CTmainFrame.JTextArea1.setText("");
      }

  • Removing Border from a JtextField

    Hi all
    how do i remove the border surrounding the JTExtfield in my applet (using jdk1.3)
    Thank You

    A brief browsing of the Java documentation (which I always keep close at hand) indicates that JComponent has the setBorder() method. A website mentioned in the setBorder part gives this example (I haven't tested it):
    nameOfTextField.setBorder(BorderFactory.createEmptyBorder());Here is the site I extracted it from:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html

  • Sound im my file

    Hi, here the code:
    import java.awt.*;
    import java.io.FileInputStream;
    import java.applet.*;
    import sun.audio.*;
    import hsa.Console;
    import java.awt.*;
    import java.io.FileInputStream;
    import java.applet.*;
    import sun.audio.*;
    import hsa.Console;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.applet.*;
    public class PlayMusic
    static JTextArea Musicarea;
    JFrame frame3;
    // Create an array for five pieces of music
    static AudioData[] audioData = new AudioData [5];
    static AudioDataStream[] audioStream = new AudioDataStream [5];
    static ContinuousAudioDataStream[] continuousAudioDataStream =
    new ContinuousAudioDataStream [5];
    public void Music ()
    frame3 = new JFrame ("Box");
    frame3.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    addComponentsToPane3 (frame3.getContentPane ());
    frame3.pack ();
    frame3.setSize (330, 300);
    frame3.setLocationRelativeTo (null);
    frame3.setVisible (true);
    public void addComponentsToPane3 (Container pane3)
    pane3.setLayout (null);
    Musicarea = new JTextArea ();
    Musicarea.setEditable (false);
    Musicarea.setBounds (0, 0, 330, 210);
    pane3.add (Musicarea);
    public static void main (String[] args)
    char c;
    int choice, newChoice;
    int ch = 0;
    // JFrame c = new JFrame
    /* c.println ("This program will randomly play one of five pieces " +
    "music. It will start a");
    c.println ("different piece of music each time you press a key. " +
    "Press 'q' to quit"); */
    //c.print ("\nLoading music... ");
    loadMusic ("music0.au", 0);
    loadMusic ("music1.au", 1);
    loadMusic ("music2.au", 2);
    loadMusic ("music3.au", 3);
    loadMusic ("music4.au", 4);
    // c.println ("Done.");
    choice = (int) (Math.random () * 5);
    // Musicarea.setText ("\nPlaying song #" + choice);
    while (true)
    Musicarea.setText ("\nPlaying song #" + choice);
    loop (choice);
    //ch = c.getChar ();
    if (ch == 'q')
    break;
    do
    newChoice = (int) (Math.random () * 5);
    while (choice == newChoice);
    stop (choice);
    choice = newChoice;
    } // main method
    static void loadMusic (String fileName, int index)
    try
    FileInputStream fis = new FileInputStream (fileName);
    AudioStream tempAudioStream = new AudioStream (fis);
    audioData [index] = tempAudioStream.getData ();
    audioStream [index] = null;
    continuousAudioDataStream [index] = null;
    catch (Exception e)
    System.out.println ("Unable to load " + fileName + ": " + e);
    System.exit (0);
    } // loadMusic method
    static void loop (int index)
    continuousAudioDataStream [index] =
    new ContinuousAudioDataStream (audioData [index]);
    AudioPlayer.player.start (continuousAudioDataStream [index]);
    } // loop (void)
    static void play (int index)
    audioStream [index] = new AudioDataStream (audioData [index]);
    AudioPlayer.player.start (audioStream [index]);
    } // play (void)
    static void stop (int index)
    if (audioStream [index] != null)
    AudioPlayer.player.stop (audioStream [index]);
    if (continuousAudioDataStream [index] != null)
    AudioPlayer.player.stop (continuousAudioDataStream [index]);
    } // stop ()
    } // PlayMusic classI have made some mistakes that i dont know how to fix, what i want is for the five tracks to play in random order in a JFrame, can someone please take a look and see if you can help?
    thanks alot
    Message was edited by:
    GraDoN

    Hi,
    I tried your code and i successfully play 4 files randomly and continuously but only problem is that it showing one exception that
    Exception in thread "main" java.lang.IllegalThreadStateException
         at java.lang.Thread.start(Thread.java:571)
         at PlayMusic.main(PlayMusic.java:83)
    becoz of one method that i used extra. if i remove that one it doesn't play.
    I am giving the working ocde here. If any one find the reason for that exception thn plz let me know.
    *************code start from here *******************
    import java.awt.*;
    import java.io.FileInputStream;
    import java.applet.*;
    import sun.audio.*;
    //import hsa.Console;
    import java.awt.*;
    import java.io.FileInputStream;
    import java.applet.*;
    import sun.audio.*;
    //import hsa.Console;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.applet.*;
    public class PlayMusic
         static JTextArea Musicarea;
         JFrame frame3;
         // Create an array for five pieces of music
         static AudioData[] audioData = new AudioData [4];
         static AudioDataStream[] audioStream = new AudioDataStream [4];
         static ContinuousAudioDataStream[] continuousAudioDataStream =new ContinuousAudioDataStream [4];
         public void Music ()
              frame3 = new JFrame ("Box");
              frame3.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              addComponentsToPane3 (frame3.getContentPane ());
              frame3.pack ();
              frame3.setSize (330, 300);
              frame3.setLocationRelativeTo (null);
              frame3.setVisible (true);
         public void addComponentsToPane3 (Container pane3)
              pane3.setLayout (null);
              Musicarea = new JTextArea ();
              Musicarea.setEditable (false);
              Musicarea.setBounds (0, 0, 330, 210);
              pane3.add (Musicarea);
         public static void main (String[] args)
              char c;
              int choice, newChoice;
              int ch = 0;
              loadMusic ("/home/araghuvanshi/Desktop/my_clonefone_files/media_0.wav", 0);
              loadMusic ("/home/araghuvanshi/Desktop/my_clonefone_files/media_1.wav", 1);
              loadMusic ("/home/araghuvanshi/Desktop/my_clonefone_files/media_2.wav", 2);
              loadMusic ("/home/araghuvanshi/Desktop/my_clonefone_files/media_3.wav", 3);
              choice = (int) (Math.random () * 4);
              String t=""+choice;
              //Musicarea.setText ("\nPlaying song #" + choice);
              int i=0;
              while (i<4)
                   i++;
                   System.out.println(choice);
                   //Musicarea.setText ("\nPlaying song #" + choice);
                   //System.out.println(t);
                   //Musicarea.setText(t);
                   loop (choice);
                   //ch = c.getChar ();
                   if (ch == 'q')
                   break;
                   do
                        newChoice = (int) (Math.random () * 4);
                   while (choice == newChoice);
                   AudioPlayer.player.start();
                   stop (choice);
                   choice = newChoice;
         } // main method
         static void loadMusic (String fileName, int index)
              try
                   FileInputStream fis = new FileInputStream (fileName);
                   AudioStream tempAudioStream = new AudioStream (fis);
                   audioData [index] = tempAudioStream.getData ();
                   audioStream [index] = null;
                   continuousAudioDataStream [index] = null;
              catch (Exception e)
                   System.out.println ("Unable to load " + fileName + ": " + e);
                   System.exit (0);
         } // loadMusic method
         static void loop (int index)
              System.out.println("Index====="+index);
              continuousAudioDataStream [index] =     new ContinuousAudioDataStream (audioData [index]);
              AudioPlayer.player.start (continuousAudioDataStream [index]);
         } // loop (void)
         static void play (int index)
              audioStream [index] = new AudioDataStream (audioData [index]);
              AudioPlayer.player.start (audioStream [index]);
         } // play (void)
         static void stop (int index)
              if (audioStream [index] != null)
              AudioPlayer.player.stop (audioStream [index]);
              if (continuousAudioDataStream [index] != null)
              AudioPlayer.player.stop (continuousAudioDataStream [index]);
         } // stop ()
    } // PlayMusic class
    All the Best.
    Regards,
    Anil R

  • ?? Several applications with one JVM ??

    Hi,
    I need to run several swing application with a single JVM. (for performance reasons, especially with memory). This is ok.
    But swing applications uses only one AWT-Event-Thread that is shared by all applications (Frames).
    The consequence is, per example, that a modal dialog in one of the applications will block all other running applications.
    Actually, this problem is bug-id = 4080029.
    But there's no workaround.
    Is there anyone who knows how to deal with this ??
    I read an article about AppContext where I understand that it should be possible to assign a different context to each application, and also a different EventQueue to each application.
    But I cannot find any documentation about AppContext, and can't understand how to use it.
    Is there someone who can help with AppContext ??
    -Herbien (Switzerland)

    I've found the following in the src directory of JDK1.3.1 -- it's supposed to be part of javax.swing but I can't find it documented anywhere, so here goes (don't forget the Dukes if this helps):
    V.V.
    * @(#)AppContext.java     1.7 00/02/02
    * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved.
    * This software is the proprietary information of Sun Microsystems, Inc. 
    * Use is subject to license terms.
    package javax.swing;
    import java.util.Hashtable;
    import java.util.Enumeration;
    * The AppContext is a per-SecurityContext table which stores application
    * service instances.  (If you are not writing an application service, or
    * don't know what one is, please do not use this class.)  The AppContext
    * allows applet access to what would otherwise be potentially dangerous
    * services, such as the ability to peek at EventQueues or change the
    * look-and-feel of a Swing application.<p>
    * Most application services use a singleton object to provide their
    * services, either as a default (such as getSystemEventQueue or
    * getDefaultToolkit) or as static methods with class data (System).
    * The AppContext works with the former method by extending the concept
    * of "default" to be SecurityContext-specific.  Application services
    * lookup their singleton in the AppContext; if it hasn't been created,
    * the service creates the singleton and stores it in the AppContext.<p>
    * For example, here we have a Foo service, with its pre-AppContext
    * code:<p>
    * <code><pre>
    *    public class Foo {
    *        private static Foo defaultFoo = new Foo();
    *        public static Foo getDefaultFoo() {
    *            return defaultFoo;
    *    ... Foo service methods
    *    }</pre></code><p>
    * The problem with the above is that the Foo service is global in scope,
    * so that applets and other untrusted code can execute methods on the
    * single, shared Foo instance.  The Foo service therefore either needs
    * to block its use by untrusted code using a SecurityManager test, or
    * restrict its capabilities so that it doesn't matter if untrusted code
    * executes it.<p>
    * Here's the Foo class written to use the AppContext:<p>
    * <code><pre>
    *    public class Foo {
    *        public static Foo getDefaultFoo() {
    *            Foo foo = (Foo)AppContext.getAppContext().get(Foo.class);
    *            if (foo == null) {
    *                foo = new Foo();
    *                getAppContext().put(Foo.class, foo);
    *            return foo;
    *    ... Foo service methods
    *    }</pre></code><p>
    * Since a separate AppContext exists for each SecurityContext, trusted
    * and untrusted code have access to different Foo instances.  This allows
    * untrusted code access to "system-wide" services -- the service remains
    * within the security "sandbox".  For example, say a malicious applet
    * wants to peek all of the key events on the EventQueue to listen for
    * passwords; if separate EventQueues are used for each SecurityContext
    * using AppContexts, the only key events that applet will be able to
    * listen to are its own.  A more reasonable applet request would be to
    * change the Swing default look-and-feel; with that default stored in
    * an AppContext, the applet's look-and-feel will change without
    * disrupting other applets or potentially the browser itself.<p>
    * Because the AppContext is a facility for safely extending application
    * service support to applets, none of its methods may be blocked by a
    * a SecurityManager check in a valid Java implementation.  Applets may
    * therefore safely invoke any of its methods without worry of being
    * blocked.
    * @author  Thomas Ball
    * @version 1.7 02/02/00
    final class AppContext {
        /* Since the contents of an AppContext are unique to each Java
         * session, this class should never be serialized. */
        /* A map of AppContexts, referenced by SecurityContext.
         * If the map is null then only one context, the systemAppContext,
         * has been referenced so far.
        private static Hashtable security2appContexts = null;
        // A handle to be used when the SecurityContext is null.
        private static Object nullSecurityContext = new Object();
        private static AppContext systemAppContext =
            new AppContext(nullSecurityContext);
         * The hashtable associated with this AppContext.  A private delegate
         * is used instead of subclassing Hashtable so as to avoid all of
         * Hashtable's potentially risky methods, such as clear(), elements(),
         * putAll(), etc.  (It probably doesn't need to be final since the
         * class is, but I don't trust the compiler to be that smart.)
        private final Hashtable table;
        /* The last key-pair cache -- comparing to this before doing a
         * lookup in the table can save some time, at the small cost of
         * one additional pointer comparison.
        private static Object lastKey;
        private static Object lastValue;
        private AppContext(Object securityContext) {
            table = new Hashtable(2);
            if (securityContext != nullSecurityContext) {
                if (security2appContexts == null) {
                    security2appContexts = new Hashtable(2, 0.2f);
                security2appContexts.put(securityContext, this);
         * Returns the appropriate AppContext for the caller,
         * as determined by its SecurityContext. 
         * @returns the AppContext for the caller.
         * @see     java.lang.SecurityManager#getSecurityContext
         * @since   1.2
        public static AppContext getAppContext() {
            // Get security context, if any.
            Object securityContext = nullSecurityContext;
    Commenting out until we can reliably compute AppContexts
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                Object context = sm.getSecurityContext();
                if (context != null) {
                    securityContext = context;
            // Map security context to AppContext.
            if (securityContext == nullSecurityContext) {
                return systemAppContext;
            AppContext appContext =
                (AppContext)security2appContexts.get(securityContext);
            if (appContext == null) {
                appContext = new AppContext(securityContext);
                security2appContexts.put(securityContext, appContext);
            return appContext;
         * Returns the value to which the specified key is mapped in this context.
         * @param   key   a key in the AppContext.
         * @return  the value to which the key is mapped in this AppContext;
         *          <code>null</code> if the key is not mapped to any value.
         * @see     #put(Object, Object)
         * @since   1.2
        public synchronized Object get(Object key) {
            if (key != lastKey || lastValue == null) {
                lastValue = table.get(key);
                lastKey = key;
            return lastValue;
         * Maps the specified <code>key</code> to the specified
         * <code>value</code> in this AppContext.  Neither the key nor the
         * value can be <code>null</code>.
         * <p>
         * The value can be retrieved by calling the <code>get</code> method
         * with a key that is equal to the original key.
         * @param      key     the AppContext key.
         * @param      value   the value.
         * @return     the previous value of the specified key in this
         *             AppContext, or <code>null</code> if it did not have one.
         * @exception  NullPointerException  if the key or value is
         *               <code>null</code>.
         * @see     #get(Object)
         * @since   1.2
        public synchronized Object put(Object key, Object value) {
            return table.put(key, value);
         * Removes the key (and its corresponding value) from this
         * AppContext. This method does nothing if the key is not in the
         * AppContext.
         * @param   key   the key that needs to be removed.
         * @return  the value to which the key had been mapped in this AppContext,
         *          or <code>null</code> if the key did not have a mapping.
         * @since   1.2
        public synchronized Object remove(Object key) {
            return table.remove(key);
         * Returns a string representation of this AppContext.
         * @since   1.2
        public String toString() {
            Object securityContext = nullSecurityContext;
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                Object context =
                    System.getSecurityManager().getSecurityContext();
                if (context != null) {
                    securityContext = context;
            String contextName = (securityContext.equals(nullSecurityContext) ?
                "null" : securityContext.toString());
         return getClass().getName() + "[SecurityContext=" + contextName + "]";
    }

  • Can't Copy text unless console is opened before applet with JTextField

    If an applet uses JTextFields, it is impossible to copy text from the console to the clipboard (or anywhere else) if the console is opened after the applet.
    See http://demo.capmon.dk/~pvm/nocopy/nocopy.html for a working applet with source and class file to try it out on...
    So if something bad has happened, and there are hints in the console e.g. a stack trace, it all has to be retyped by hand, since all Copy or export is impossible...
    Does anyone know of a workaround for this? I'd like to be able to e.g. copy stack traces to bug reports.
    Try these test cases:
    * Close all browser windows. Open a browser and visit this page. After the page with this applet has loaded, then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Select some text in the console. There is no way to put this text on the clipboard; the "Copy" button doesn't work, and neither does CTRL+Insert, CTRL+C or anything else.
    * Close all browser windows. Open a browser window no some non-java page and then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Then visit this page. Select some text in the console. Now the "Copy" button does work, enabling "export" of e.g. stack traces to other applicaitons e.g. email.
    The difference is which is opened first: The console or the applet. If you look at the very rudimentary Java source code, it is the mere creation of a JTextField is what disables or breaks the Copy functionality.
    I've tried this on Windows XP with IE 6.0 and Mozilla 1.3 and they behave exactly the same. The JVM is Sun's 1.4.2 and I've tried 1.4.1_02 also with the same behavior. I've also tried javac from both 1.4.2 and 1.4.1_01

    hey .. this seems like a bug.. can you please file a bug at
    http://java.sun.com/webapps/bugreport
    thanks...

Maybe you are looking for

  • Media controls keys does not work on iTunes?

    My keyboard has those "Media Controls Keys" on it (just like Play or Stop etc.) but it won't work with iTunes, unless iTunes is on the front of all windows. I used to use Windows Media Player and it can work with the Media Controls Keys even the play

  • SENDING EMAIL USING ORACLE9i CLIENT/SERVER

    I HAVE DOWNLOADED 2 UTILITY LIBRARIES D2KCOMN and D2KWUTIL TO MY COMPUTER. THESE 2 LIBRARIES ARE COPIED TO AN ORACLE FORM. ON THE FORM, THERS IS A BUTTON. IN THE WHEN-BUTTON-PRESSED-TRIGGER, I HAVE CODED WIN_API_SHELL.WINEXEC('"C:\PROGRAM FILES\MICRO

  • What are the new features of Oracle 10g over Oracle9i

    Hi Grus.. i want to know what are the new features of oracle 10g over Oracle 9i as well oracle 11g over 10g.. can any one give me the detailed document. Because I'm struggling each and every time while the interviewer asked above question. It's very

  • Dashboard issue after installation

    Since upgrading to Leopard, I have had only one glaring problem inside of Dashboard. WHen attempting to select a widget, or interact with one, I get the sound byte that informs me I can't perform that action. I can remove any of the widgets, but any

  • How to make a deck of cards in 2D array

    Yes you have told me to use enums but my teacher JUST told me I'd fail if i did enums. she wnats me to do it in a 2d array Ryan Reese This is like a poker simulation. Won't make it a GUI yet =/ Started December 8th, 2008 //Importing a crap load of st