Simple Question: Why does this code not exit properly?

This code is pretty simple. All I want to do is load and play a sound file in an application, but this code to load the sound file does not exit properly. I know that some resources must be allocated which I need to deallocate in order to shut down the process, but I don't know what to call to do a proper shut-down. Any help would be appreciated.
-adam
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.MalformedURLException;
import java.net.URL;
public class PlaySoundTest extends java.applet.Applet
public static void main( java.lang.String[ ] aryArgs )
java.net.URL urlSound = null;
try
urlSound = new java.net.URL( "file:/" + aryArgs[ 0 ] );
catch( java.net.MalformedURLException murle )
murle.printStackTrace( );
System.exit( 1 );
java.applet.AudioClip acSound = java.applet.Applet.newAudioClip( urlSound );

HI , If u'r still looking for the solution, this code is working on my system -
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.MalformedURLException;
import java.net.URL;
public class PlaySoundTest extends java.applet.Applet
public static void main( java.lang.String[ ] aryArgs ){
java.net.URL urlSound = null;
try{  //rahul
try
urlSound = new java.net.URL( "file:" + aryArgs[ 0 ] );
catch( java.net.MalformedURLException murle )
murle.printStackTrace( );
System.exit( 1 );
urlSound = new java.net.URL( "file:" + aryArgs[ 0 ] );
java.applet.AudioClip acSound = java.applet.Applet.newAudioClip( urlSound );
if(acSound != null){
acSound.play();
catch( Exception murle )
{        //rahul
murle.printStackTrace( );
System.exit( 1 );
}//main
The only change I made was in the URL part - file: instead of file:/ .
The other was of course to play the soundclip ...... :- ) I got really confused the first time I played it .

Similar Messages

  • Why does this code not work?

    String answer = new String("");
    in = new BufferedReader(new InputStreamReader( connection.getInputStream ()));
    String test = new String("");
    for (int i = 0 ; i < 1000 ; i++)
    answer = in.readLine();
    if (answer == null)
    System.out.println ("null");
    break;
    else
    test += answer;
    System.out.println ("answer: " + answer);
    System.out.println ("test: " + test);
    Many times, the loop will go through 2 iterations but each time, test is only equal to the first answer. The second, third, fourth etc.time it goes through the loop, it should concatenate the value of answer to the end of the string variable test. So why is it that whenever i run the program that has this code, the loop might lloop many times (let's say 2 time) but the value of test is only the first answer, and not the first answer concatenated with the second answer.

    It worked for me...my code looks like this...i used FileInputStream instead of connection..
    import java.io.*;
    class Forum {
      public static void main(String a[]) throws IOException{
        String answer = new String("");
        BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("hi.txt")));
        String test = new String("");
        for (int i = 0 ; i < 1000 ; i++)
        answer = in.readLine();
        if (answer == null)
        System.out.println ("null");
        break;
        else
        test += answer;
        System.out.println ("answer: " + answer);
        System.out.println ("test: " + test);
    my hi.txt is like this:
    fasd rea reks krie
    fsdfasd
    asdfasd
    sfasdf
    asdfasd
    The output is
    answer: fasd rea reks krie
    answer: fsdfasd
    answer: asdfasd
    answer: sfasdf
    answer: asdfasd
    null
    test: fasd rea reks kriefsdfasdasdfasdsfasdfasdfasd
    Is this not the way u want???

  • Repaint() an applet from a swing applet, why does this code not work?

    below are three files that work as planned except for the call to repaint(). This is envoked when a button is hit in one applet and it should repaint another applet. I opened them up in a html file that simply runs both applets. If you could see why the repaint doesn't work I'd love to know. good luck.
    //speech1
    import java.awt.*;
    import java.applet.Applet;
    import java.awt.event.*;
    //java extension packages
    import javax.swing.*;
    public class speechapp1 extends JApplet implements ActionListener{
    // setting up Buttons and Drop down menus
    char a[];
    Choice choicebutton;
    JLabel resultLabel;
    JTextField result;
    JLabel enterLabel;
    JTextField enter;
    JButton pushButton;
    TreeTest PicW;
    // setting up applets G.U.I
    public void init(){
    // Get content pane and set it's layout to FlowLayout
    Container container = getContentPane();
    container.setLayout( new FlowLayout() );
    // initialise buttons and shit
    a = new char[30];
    choicebutton = new Choice();
    enterLabel = new JLabel("Test");
    enter = new JTextField(30);
    resultLabel= new JLabel("speech label");
    result = new JTextField(30);
    result.setEditable(false);
    // Add items to Choice Button
    choicebutton.addItem("abc");
    choicebutton.addItem("def");
    choicebutton.addItem("ghi");
    choicebutton.addItem("jkl");
    pushButton = new JButton("Click to continue");
    // Add new Tree from file TreeTest.java
    PicW = new TreeTest();
    // Add buttons to container.
    container.add(resultLabel);
    container.add(result);
    container.add(enterLabel);
    System.out.println("");
    container.add(choicebutton);
    System.out.println("");
    container.add(pushButton);
    pushButton.addActionListener(this);
    //choicebutton.addActionListener( this );
    // Set the text in result;
    result.setText("Hello");
    //public void paint(Graphics gg){
    // result.setText("Hello");
    public void actionPerformed(ActionEvent event){
    // continue when action performed on pushButton
    String searchKey = event.getActionCommand();
    System.out.println("");
    if (choicebutton.getSelectedItem().equals("abc"))
    PicW.getPicWeight(1);
    if (choicebutton.getSelectedItem().equals("def"))
    PicW.getPicWeight(2);
    if (choicebutton.getSelectedItem().equals("ghi"))
    PicW.getPicWeight(3);
    if (choicebutton.getSelectedItem().equals("jkl"))
    PicW.getPicWeight(4);
    System.out.println("repainting from actionPerformed method()");
    PicW.repaint();
    import java.applet.Applet;
    import java.awt.*;
    import java.util.*;
    public class TreeTest extends Applet{
    Tree BackgroundImageTree;
    Tree PlayerImageTree;
    Image snow,baby;
    int weight;
    public void getPicWeight(int w){
    weight = w;
    System.out.println("the new weight has been set at: "+weight);
    this.repaint();
    public void init()
    // initialising trees for backgound images and player images
    BackgroundImageTree = new Tree();
    PlayerImageTree = new Tree();
    // initialising images and correcting size of images to correctly fit the screen
    snow = getImage(getDocumentBase(),"snow.gif");
    baby = getImage(getDocumentBase(),"baby.gif");
    // inserting images into correct tree structure
    System.out.println("inserting images into tree: ");
    // inserting background images into tree structure
    BackgroundImageTree.insertImage(1,snow);
    // inserting players into tree structure
    PlayerImageTree.insertImage(1,baby);
    public void paint(Graphics g){
    System.out.println("Searching for selected Image");
    if((BackgroundImageTree.inorderTraversal(1)==null)&&(PlayerImageTree.inorderTraversal(1)==null)){
    System.out.println("There is no tree with the selected value in the trees");
    }else{
    g.drawImage(BackgroundImageTree.inorderTraversal(1),1,3,this);
    //g.drawImage(PlayerImageTree.inorderTraversal(1),55,150,this);
    import java.awt.*;
    import java.applet.Applet;
    class TreeNode {
    TreeNode left;
    Image data;
    TreeNode right;
    int value;
    public TreeNode(int weight,Image picture){
    left = right = null;
    value = weight;
    data = picture;
    public void insert(int v, Image newImage){
    if ( v< value){
    if (left ==null)
    left = new TreeNode(v,newImage);
    else
    left.insert(v,newImage);
    else if (v>value){
    if (right ==null)
    right = new TreeNode(v,newImage);
    else
    right.insert(v, newImage);
    public class Tree{
    private TreeNode root;
    public Tree() {
    root = null;
    public void insertImage(int value, Image newImage){
    if (root == null)
    root = new TreeNode(value,newImage);
    else
    root.insert(value,newImage);
    // in order search of tree.
    public Image inorderTraversal(int n)
    return(inorderHelper(root,n));
    private Image inorderHelper(TreeNode node, int n){
    Image temp = null;
    if (node == null)
    return null;
    if (node.value == n ){
    return(node.data);
    temp = inorderHelper(node.left,n);
    if (temp == null){
    temp = inorderHelper(node.right,n);
    return temp;
    }

    I can fix your problems
    1. You get an error here because you can only invoke the superclass's constructor in the subclass's constructor. It looks like that's what you're trying to do, but you're not doing it right. Constructors don't return any value (actually they do, but it's implied, so you don't need the void that you've got in your code)
    2. I'm not sure, but I think your call to show might be wrong. Move the setsize and setvisible calls to outside of the constructor

  • WHY DOES THIS SQL NOT WORK

    I have 4 statements.
    echo off
    plus80 / @z:\nesp1483_batch
    plus80 / @z:\nesp1484a_batch
    exit
    The first statement plus80 / @z:\nesp1484_batch inserts records into a table and creates a report and deletes the table.
    However the second statement plus80 / @z:\nesp1484a_batch is not working properly. I want it to insert records into a table, create a report and then delete the table but it is not working properly. It is hanging up on this statement.
    I need to say plus80 to get the program to execute properly.
    I have also tried sqlplus /@z:\nesp1484a_batch but this does not work either.
    What do I need to do to make the third statement to execute properly?

    I know that it is not working
    because the response time is slow and I have over 15 minutes
    and nothing is happening. How do you know it is not working as opposed to just working slow?
    Do you have any logging routines in your code? If you have, switch on them on and see what's happening. If not, now is a good time to think about including them...
    Cheers, APC

  • Why does this websites not work on our Mac products?

    http://www.gordonbennett2012.ch/
    We are working on the above website: We cannot get it to work on the following Mac devises. Would you please advise the reason for this and how we can fix it?
    From: FLY GAS
    Subject: Fwd: Website of Gordon Bennett 2012  
    Date: August 11, 2012 1:52:22 PM MDT
    To: René Louis  Cc: Mark Sullivan
    Hello René,   Thank you very much for your email. I am happy to work with you. I have been working on this all day. I still have not figured out why this is not working. I am Mark Sullivan and Cheri White's Crew Chief/Technical Support for the USA.
    The following products are being used:
    MacBook Pro,Mac OS X Version 10.7.4, Processor 2.8 GHz Intel Core 2 Duo
    Mac iPad, Version 5.1.1 (9B206)
    Non of these prodects will upload your site    http://www.gordonbennett2012.ch/
    I have tried the following browsers:
    Opera: Could not connect to remote server,
    Safari: no responce
    Firefox: The connection has timed out                                                                The server at gordonbennett2012.ch is taking too long to respond.
    Google Chrome: Oops! Google Chrome could not connect to www.gordonbennett2012.ch
    I have had all our crew do the same. They are in different parts of the USA.
    And the response has been the following:
    North Carolina on PC and Android: Site uploaded
    New Mexico on PC and iPhone: Site did not upload on either
    New Mexico on PC and iPhone: Site did upload
    I have also contacted Mac. Please let me know your thoughts so we can sort this out.  In the past I have been able to get your site. Just in the past month I have not been able to. I am getting a timed out error from ALL the above browsers.
    Kind regards,  Letitia
    Ms. Letitia Hill
    TEAM USA/FLY GAS
    PO Box 7186
    Albuquerque, New Mexico 87194 USA
    TEL: 505-270-6759
    FAX: 505-503-8430
    E-Mail: [email protected]
    Website: www.flygas.net
    Begin forwarded message:
    From: René Louis 
    Subject: Website of Gordon Bennett 2012 Date: August 11, 2012 1:25:13 PM MDT
    To: [email protected]
    Dear Letitia  Thank you very much for your message about our website.
    I am also working with a Mac and could not find any problems.  I would be very interested to know which products you are using and what is not working so I could have a detailed look at it.
    Thank you very much.
    Best Regards
    René
    Gordon Bennett 2012 Secretariat / Postfach 280 / CH-9650 Nesslau / Switzerland www.gordonbennett2012.ch  René Louis / Kirchweg 672 / CH-9650 Nesslau / Switzerland

    There seems to be a block with the Internet server in the United States as other Internet and cell servers i.e. Verizon and Century-Link DSL work with Mac, Andriod and PC. It just seems to be Mac on Comcast that is not...
    Without more data I'm inclined to say it's more likely to be Comcast itself, rather than 'Macs on Comcast'.
    For example, do other devices (PCs, Android, iOS) on that Comcast network also have problems connecting? or do they connect fine?
    I'd expect that any device at that network has a problem, which indicates a problem with Comcast. It might be their DNS not resolving properly, or them not routing data correctly, but that should be your focus.
    Perform a DNS lookup on the www.gordonbennett2012.ch hostname. What result do you get? Is it the expected address?
    If that returns the right address, what do you get with a traceroute?
    That will test the routing befween your system and the server, and may indicate other problems on the network.

  • Why does this code fail in command line?

    I am using the "ListDemo" from the java swing tutorial. If I compile it on the command line
    javac ListDemo.java
    It compiles fine. Then when I run it, it says:
    C:\Development\Java\Projects\Projects>java ListDemo
    Exception occurred during event dispatching:
    java.lang.NoSuchMethodError
    at ListDemo.createAndShowGUI(ListDemo.java:196)
    at ListDemo.access$400(ListDemo.java:7)
    at ListDemo$1.run(ListDemo.java:217)
    at java.awt.event.InvocationEvent.dispatch(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.run(Unknown Source)
    Yet when I load up the same file into Netbeans, it compiles and runs fine! Here is the file:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    /* ListDemo.java is a 1.4 application that requires no other files. */
    public class ListDemo extends JPanel
                          implements ListSelectionListener {
        private JList list;
        private DefaultListModel listModel;
        private static final String hireString = "Hire";
        private static final String fireString = "Fire";
        private JButton fireButton;
        private JTextField employeeName;
        public ListDemo() {
            super(new BorderLayout());
            listModel = new DefaultListModel();
            listModel.addElement("Alan Sommerer");
            listModel.addElement("Alison Huml");
            listModel.addElement("Kathy Walrath");
            listModel.addElement("Lisa Friendly");
            listModel.addElement("Mary Campione");
            listModel.addElement("Sharon Zakhour");
            //Create the list and put it in a scroll pane.
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            list.setVisibleRowCount(5);
            JScrollPane listScrollPane = new JScrollPane(list);
            JButton hireButton = new JButton(hireString);
            HireListener hireListener = new HireListener(hireButton);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(hireListener);
            hireButton.setEnabled(false);
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(hireListener);
            employeeName.getDocument().addDocumentListener(hireListener);
            String name = listModel.getElementAt(
                                  list.getSelectedIndex()).toString();
            //Create a panel that uses BoxLayout.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane,
                                               BoxLayout.LINE_AXIS));
            buttonPane.add(fireButton);
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(employeeName);
            buttonPane.add(hireButton);
            buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            add(listScrollPane, BorderLayout.CENTER);
            add(buttonPane, BorderLayout.PAGE_END);
        class FireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                //so go ahead and remove whatever's selected.
                int index = list.getSelectedIndex();
                listModel.remove(index);
                int size = listModel.getSize();
                if (size == 0) { //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else { //Select an index.
                    if (index == listModel.getSize()) {
                        //removed item in last position
                        index--;
                    list.setSelectedIndex(index);
                    list.ensureIndexIsVisible(index);
        //This listener is shared by the text field and the hire button.
        class HireListener implements ActionListener, DocumentListener {
            private boolean alreadyEnabled = false;
            private JButton button;
            public HireListener(JButton button) {
                this.button = button;
            //Required by ActionListener.
            public void actionPerformed(ActionEvent e) {
                String name = employeeName.getText();
                //User didn't type in a unique name...
                if (name.equals("") || alreadyInList(name)) {
                    Toolkit.getDefaultToolkit().beep();
                    employeeName.requestFocusInWindow();
                    employeeName.selectAll();
                    return;
                int index = list.getSelectedIndex(); //get selected index
                if (index == -1) { //no selection, so insert at beginning
                    index = 0;
                } else {           //add after the selected item
                    index++;
                listModel.insertElementAt(employeeName.getText(), index);
                //If we just wanted to add to the end, we'd do this:
                //listModel.addElement(employeeName.getText());
                //Reset the text field.
                employeeName.requestFocusInWindow();
                employeeName.setText("");
                //Select the new item and make it visible.
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            //This method tests for string equality. You could certainly
            //get more sophisticated about the algorithm.  For example,
            //you might want to ignore white space and capitalization.
            protected boolean alreadyInList(String name) {
                return listModel.contains(name);
            //Required by DocumentListener.
            public void insertUpdate(DocumentEvent e) {
                enableButton();
            //Required by DocumentListener.
            public void removeUpdate(DocumentEvent e) {
                handleEmptyTextField(e);
            //Required by DocumentListener.
            public void changedUpdate(DocumentEvent e) {
                if (!handleEmptyTextField(e)) {
                    enableButton();
            private void enableButton() {
                if (!alreadyEnabled) {
                    button.setEnabled(true);
            private boolean handleEmptyTextField(DocumentEvent e) {
                if (e.getDocument().getLength() <= 0) {
                    button.setEnabled(false);
                    alreadyEnabled = false;
                    return true;
                return false;
        //This method is required by ListSelectionListener.
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
                } else {
                //Selection, enable the fire button.
                    fireButton.setEnabled(true);
         * 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.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ListDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ListDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //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();

    You are not running this code under JDK 1.4
    The setDefaultLookAndFeelDecorated method requires JDK 1.4 version.

  • Why does this expression not work as I'd hoped?

    I have a Black Solid 3 with a CC Particle World placed within it. I have some particles set up to run at 0.01 velocity outward from the center of my composition. I've put the following expression on the Velocity setting:
    value = thisComp.layer("Audio Amplitude").effect("Both Channels")("Slider");
    if (value > 50) 20 else 0.01
    The Audio Amplitude layer it is linked to is a auto-keyframe layer created from a .mp3 file - the values that it hits during the most intense part of the song range from 1 to around 85-90.
    Why does my velocity setting remain at 0.01 consistently, despite it being clearly evident that the Audio Amplitude layer is going far over 50.
    P.S.: If I change the > sign to a < sign, it stays at 20. Why?
    EDIT: Okay, it seems the issue was having the variable named as 'value'. Now that it works, it still doesn't seem to work as intended - I'd wanted the particles to move very slowly outward, and then whenever bass was detected, to speed up, until the bass was no longer detected, in which case it would return to a slow pace again, anyone have any idea how I'd go about doing this?
    Message was edited by: James Wingate

    One way is to prepare a "Remap Speed" slider somewhere in the comp that will control the remapping speed, and animate it.
    0 = time lock, 1 = normal speed, 2 = speedx2, etc
    Then in the time remap property of the layer, set this expression:
    s = [pickwhip the "Remap Speed" slider]
    t=inPoint;    // normal time
    T=inPoint;    // remapped time
    dt = thisComp.frameDuration;
    TIME = time-0.001;
    while (t<TIME){
        T+= s.valueAtTime(t) * dt;
        t+=dt;
    T;
    Ok i reread the original post again, in your case the "Remap Speed" slider could have the expression:
    value = thisComp.layer("Audio Amplitude").effect("Both Channels")("Slider");
    if (value > 50) 1 else 0.01          // above 50 : normal speed, under : very small speed

  • Why does this MagicMouse not scroll pages?

    I have a new iMac purchased today. It has the MagicMouse and for some reason that is not working properly.
    When I swipe my finger over the mouse (up or down) the web page or application window does not scroll. I have to move the mouse over to the scroll bar, grab it and scroll that way.
    Can someone tell me what might be wrong with this?

    Look in System Preferences > Universal Access > Mouse & Trackpad tab > Mouse options... button > Check scrolling.
    Regards,
    Captfred

  • Why does this code always gotoAndStop at the same frame?

    The symbol "alldoor" contains the following six frames in sequential order: "door1","red_door1","door2","red_door2","door3" and "red_door3".
    var doors:Array =["door1", "door2", "door3"];
    var doorSelector:String = doors[newDoors(0, doors.length - 1)]
    function newDoors (min:Number, max:Number):Number
    var  doorColors:Number = Math.round(Math.random() * (min - max) + max);
    return doorColors;
    alldoor.gotoAndStop(doorSelector);
    alldoor.addEventListener(MouseEvent.CLICK,changeColors );
    function changeColors(e:MouseEvent)
        if (e.currentTarget.currentLabel == doorSelector)
            e.currentTarget.gotoAndStop(currentFrame + 1);
         I am attempting to get this code select one of the frames starting with the string "door" at start up. Then, the door should move to the frame
    directly following it on the timeline when clicked. However, as the code is written, the frame always jumps to the second frame in the symbol,regardless of what the current label is. What should I change?

    either:
    1.  those frames aren't loaded when that code executes or
    2.  you don't have those labels on the timeline that contains that code or
    3.  there is other code executing after your goto changing your frame
    use the trace() function to debug and find which is your problem.

  • Why does my Facebook not work properly since loading yosemite and why does it ask me to load java runtime overtime I log in

    My Facebook does not run properly since upgrading to yosemite, some sections i can't get in and you see the waiting clock then safari says it can't find it, not all photos load properly, also keep on getting you need to load java runtime overtime I log on even though it has verified it.

    It works completly fine in applet viewer, im at a loss here

  • Why does my ipad not work properly when charging

    when my ipad is plugged to charger it does not work properly  goes crazy

    Not sure what 'goes crazy' means but it most likely should not do that.  Try a reset... press the home and sleep/lock buttons until you see the Apple logo, ignoring the slider. Takes about 5-15 secs of button holding and you won't lose any data or settings.
    Also try it plugged into another outlet (on another circuit) and/or try another charger.

  • Why does this class not read and write at same time???

    I had another thread where i was trying to combine two class files together
    http://forum.java.sun.com/thread.jspa?threadID=5146796
    I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class testing extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
       //private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
       private Employee record;
    //////////////////////////////////////from read
    private ObjectInputStream input;
       private JButton nextButton, openButton, nextRecordButton ;
       private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
    /////////////////////////////////////////////from read end
       // set up GUI
       public testing()
          super( "Employee Data" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // nine textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          SaveAs = userInterface.getSaveAsButton();
          SaveAs.setText( "Save as.." );
    //////////////////from read
    openButton = userInterface.getOpenFileButton();
          openButton.setText( "Open File" );
    openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    ///////////from read end
          // register listener to call openFile when button pressed
          SaveAs.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   SaveLocation();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          SaveToFile = userInterface.getSaveStoreToFileButton();
          SaveToFile.setText( "Save to store and to file need to split this task up" );
          SaveToFile.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          SaveToFile.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
             } // end anonymous inner class
          ); // end call to addActionListener
    Exit = userInterface.getExitAndSaveButton();
          Exit.setText( "Exit " );
          Exit.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          Exit.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // adds record to to file
                   closeFile(); // closes everything
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
    ////////////////from read
      // enable user to select file to open
       private void openFile()
          // display file dialog so user can select file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                input = new ObjectInputStream(
                   new FileInputStream( fileName ) );
                openButton.setEnabled( false );
                nextButton.setEnabled( true );
             // process exceptions opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
    public void readRecord() // need to merger with next record
          Employee record;
          // input the values from the file
          try {
         record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);/////////ADDS record to Store
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
    // i added all those bits above split onto one line to look neater
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
       private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record content
    ///////////////////////////////////from read end
    private void SaveLocation()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                SaveAs.setEnabled( false );
                SaveToFile.setEnabled( true );
              Exit.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
    private void closeFile()
          // close file
          try {
              //you want to cycle through each recordand add them to store here.
                                            int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
    input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0)); // check if m or f prob check in employee
    if ( employeeNumber >= 0 ) {
                  /* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                                  //output.writeObject( record );
                   output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new testing();
    } // end class CreateSequentialFile

    Sure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
    I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
    So now we have a Big Ball Of Tar&trade; and I feel partly responsible.

  • Chart timestamp accelerating - why does this VI not work?

    In fighting with TDMS files, I decided to experiment with a different approach to get what I need - a stripchart with a long history, that I can pause and scroll back through to look for anomolies.  Came up with a clever (I thought) approach to it...  Not the most elegant, but it should work.  In the attached VI, I have 2 charts simulating my data on the left, and 2 charts that will be my scrollable history on the right.  I worked out how to apply a correct timestamp to the charts, and am basically just passing the history from the source chart to the history one - unless the "pause" button is on, which allows me to scroll back.  All of the charts are set with a window of 300 points, and the VI cycles at 200ms, so it should be a 1 minute active window before it scrolls off the edge and into the buffer.  The chart buffer size is set for 180000 for each chart, which should be 10 hours of data at this polling rate.
    I start the program, everything is fine.  Both sets of charts begin populating, the timestamp is chugging away in 1 second intervals, it looks beautiful.  Then it all falls apart.  Once the chart is full, and begins scrolling, the timestamp goes nuts and begins accelerating.  It takes exactly 1 minute to fill the chart from empty, then the timestamp starts flying much faster - at least twice the speed, as the data being collected (and the actual time elapsed).  I haven't been able to determine if it is a set multiplier in speed, or if it is ramping up faster and faster.
    So...  How is this possible?  I can't see what the code could be doing to cause this.  It's so very frustrating, because the pause and scroll feature works perfectly, just like I planned it.  But without an accurate timestamp, this is completely useless.
    Edit - oops, attached old version of VI, updated with correct one now.
    Attachments:
    Advanced Chart with Timestamp.vi ‏30 KB

    I didn't run the code, but it sounds like this - http://lavag.org/topic/16789-chart-scale-falling-out-of-sync-with-data-grid/ . You can check if he found a solution.
    Personally, I tend to use XY graphs because they allow more control and don't require a single dx for all points. They are more of a pain because you have to buffer the data yourself, but the code for that is reasonably easy and I believe there's an XY chart example in the example finder.
    Try to take over the world!

  • Why does this video not support on my ipod?

    Hey, i imported a video with handbrake and decided to put in the chapter markers. But this video when i added it to itunes and i plug my ipod in, it says that it isn't able to transfer it onto my ipod because my ipod doesn't support this kind of video. This video should work because the bitrate is 1500kbps and 160kbps for audio. The size is 720x384. And i have other videos that size on my ipod so i know this isn't the problem. But i just need to know why this is happenin.

    The error $ is not defined means that the jQuery library isn't loading correctly. The page is loading the library from Google rather than from the site itself.
    When you have a problem with one particular site, a good "first thing to try" is clearing your Firefox cache and deleting your saved cookies for the site.
    (1) Bypass Firefox's Cache
    Use Ctrl+Shift+r to reload the page fresh from the server.
    Alternately, you also can clear Firefox's cache completely using:
    orange Firefox button (or Tools menu) > Options > Advanced
    On the Network mini-tab > Cached Web Content : "Clear Now"
    If you have a large hard drive, this might take a few minutes.
    (2) Remove your google.com cookies (save any pending work first). You can call up the cookie dialog anywhere on google.com using:
    * right-click and choose View Page Info > Security > "View Cookies"
    * Alt+t (open the classic Tools menu) > Page Info > Security > "View Cookies"
    Or if you call it up from another site, change the site in the search box at the top of the dialog to google.com. Then you can remove your Google cookies individually.
    Then try reloading the page. Does that help?
    If jQuery still won't load, review your extensions for any designed to reduce cross-site interactions or targeting Google or privacy. You can review those here:
    orange Firefox button (or Tools menu) > Add-ons > Extensions category

  • Why does this code crash the flash 10.2 plugin?

    A very simple piece of code that causes the flash 10.2 plugin container to crash on all platforms, but does not crash on 10.1 player.
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="300" minHeight="200">
         <fx:Script>
              <![CDATA[
                   import mx.controls.Alert;
                   private function crash(type:int, ...additionalArgs):void {
                        var msg:String;
                        switch (type) {
                             case 1: msg = "Crashes!"; break;
                             case 2: msg = additionalArgs[0]; break;
                        Alert.show("Crash : " + msg);
                   private function notCrash(type:int, ...additionalArgs):void {
                        // Does nothing at all, but stops the crash....
                        if (additionalArgs) {}
                        var msg:String;
                        switch (type) {
                             case 1:msg = "Not crash"; break;
                             case 2: msg = additionalArgs[0]; break;
                        Alert.show("NotCrash : " + msg);
              ]]>
         </fx:Script>
         <s:Button label="Does not crash flash" click="notCrash(2,'value')" x="10" y="10"/><s:Button label="Crash flash" click="crash(2,'value')" x="150" y="10"/>
    </s:Application>

    Crash long on Safari :
    Process:         WebKitPluginHost [43418]
    Path:            /System/Library/Frameworks/WebKit.framework/WebKitPluginHost.app/Contents/MacOS/WebKitPluginHost
    Identifier:      com.apple.WebKit.PluginHost
    Version:         6533 (6533.13)
    Build Info:      WebKitPluginHost-75331300~12
    Code Type:       X86 (Native)
    Parent Process:  WebKitPluginAgent [43105]
    PlugIn Path:       /Library/Internet Plug-Ins/Flash Player.plugin/Contents/PlugIns/FlashPlayer-10.6.plugin/Contents/MacOS/FlashPlayer-10.6
    PlugIn Identifier: com.macromedia.FlashPlayer-10.6.plugin
    PlugIn Version:    10.2.152.26 (10.2.152.26)
    Date/Time:       2011-02-22 21:56:12.733 +0200
    OS Version:      Mac OS X 10.6.6 (10J567)
    Report Version:  6
    Exception Type:  EXC_BAD_ACCESS (SIGBUS)
    Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000010
    Crashed Thread:  0  Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
    0   ...dia.FlashPlayer-10.6.plugin     0x140043ee main + 1461822
    1   ???                                0x1d9db79f 0 + 496875423
    2   ???                                0x1d9db8b3 0 + 496875699
    3   ???                                0x1d9db937 0 + 496875831
    4   ...dia.FlashPlayer-10.6.plugin     0x140068c6 main + 1471254
    5   ...dia.FlashPlayer-10.6.plugin     0x140087d7 main + 1479207
    6   ...dia.FlashPlayer-10.6.plugin     0x13a9f658 0x139ca000 + 874072
    7   ...dia.FlashPlayer-10.6.plugin     0x13a989e1 0x139ca000 + 846305
    8   ...dia.FlashPlayer-10.6.plugin     0x13aa48de 0x139ca000 + 895198
    9   ...dia.FlashPlayer-10.6.plugin     0x13ba6572 0x139ca000 + 1951090
    10  ???                                0x194083b5 0 + 423658421
    11  ???                                0x1c7fee20 0 + 478146080
    12  ???                                0x1dbe2844 0 + 499001412
    13  ???                                0x1db3d61c 0 + 498325020
    14  ???                                0x1db3dcfc 0 + 498326780
    15  ???                                0x1db37b5c 0 + 498301788
    16  ...dia.FlashPlayer-10.6.plugin     0x13a9f658 0x139ca000 + 874072
    17  ...dia.FlashPlayer-10.6.plugin     0x13aa06b6 0x139ca000 + 878262
    18  ...dia.FlashPlayer-10.6.plugin     0x13bb42be 0x139ca000 + 2007742
    19  ...dia.FlashPlayer-10.6.plugin     0x13d407c8 0x139ca000 + 3631048
    20  ...dia.FlashPlayer-10.6.plugin     0x13d40eab 0x139ca000 + 3632811
    21  ...dia.FlashPlayer-10.6.plugin     0x13ea39c7 main + 17431
    22  com.apple.CoreFoundation           0x950184cb __CFRunLoopDoSources0 + 1563
    23  com.apple.CoreFoundation           0x95015f8f __CFRunLoopRun + 1071
    24  com.apple.CoreFoundation           0x95015464 CFRunLoopRunSpecific + 452
    25  com.apple.CoreFoundation           0x95015291 CFRunLoopRunInMode + 97
    26  com.apple.HIToolbox                0x901a8004 RunCurrentEventLoopInMode + 392
    27  com.apple.HIToolbox                0x901a7dbb ReceiveNextEventCommon + 354
    28  com.apple.HIToolbox                0x901a7c40 BlockUntilNextEventMatchingListInMode + 81
    29  com.apple.AppKit                   0x9130978d _DPSNextEvent + 847
    30  com.apple.AppKit                   0x91308fce -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 156
    31  com.apple.AppKit                   0x912cb247 -[NSApplication run] + 821
    32  com.apple.WebKit.PluginHost        0x1842240f 0x18421000 + 5135
    33  com.apple.WebKit.PluginHost        0x1842204d 0x18421000 + 4173

Maybe you are looking for

  • Speed problems in Tampa?

    Are there any known issues going on in Tampa the past couple of days? Since Monday afternoon my speeds have consistently tested at around .5 Mbps up and down.  Prior to that I would consistently get 22-25 Mbps down and 12-15 Mbps up.  I'm on the 25/1

  • FLEX and CF Debugger setup - PLEASE HELP

    I can't get the line debugger for CF in eclipse to work for the life of me. I've been trying this for over 8 hours now. I follow the directions on all the tutorials out there on the web and still no luck. All my CF admin settings are correct. I think

  • AGO Function for the next to Years

    Hello together, is it possible to use the AGO - Funktion for Values in the Future? It is just the negative usage of the function. Regards, Stefan

  • Is there a possibility of including a another app in my folio?

    Is there a possibility of including an another app in my folio? I do mean to have a possibility to go to another app which is already installed on the same iPad? I do have a possibility to place a hyperlink to a URL. Can I place a hyperlink to an ano

  • Software Monitoring

    When my **** singers record their vocals they always prefer some effects to be heard while they sing, like reverb and delay. Well I have set my input 1 for the vocals in my Presonus FB as a mono track. I always put in a compressor in that track and i