** Please Help. When I call this class, it causes the program to stop responding? Actually I used a button must be clicked to start call the class in another class to run it. after I press that button it causes the program GUI to stop responding. I am developing a virtual classroom so by this code, it broadcast voice from the server to the clients, so please help.**

    //this is the class:

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.Mixer;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.TargetDataLine;
   public class sender {

        ServerSocket MyService;
        Socket clientSocket = null;
        BufferedInputStream input;
        TargetDataLine targetDataLine;

        BufferedOutputStream out;
        ByteArrayOutputStream byteArrayOutputStream;
        AudioFormat audioFormat;    
        SourceDataLine sourceDataLine;    
        byte tempBuffer[] = new byte[10000];

            public sender() throws LineUnavailableException{


                    try {
                audioFormat = getAudioFormat();
                DataLine.Info dataLineInfo =  new DataLine.Info(SourceDataLine.class,audioFormat);     
                sourceDataLine = (SourceDataLine)
                AudioSystem.getLine(dataLineInfo);
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                MyService = new ServerSocket(5000);

                clientSocket = MyService.accept();
                captureAudio();
                input = new BufferedInputStream(clientSocket.getInputStream()); 
                out=new BufferedOutputStream(clientSocket.getOutputStream());

                while(input.read(tempBuffer)!=-1){          
                    sourceDataLine.write(tempBuffer,0,10000);
                }
            } catch (IOException e) {

                e.printStackTrace();
            }


        }

             private AudioFormat getAudioFormat(){
                float sampleRate = 8000.0F;       
                int sampleSizeInBits = 16;         
                int channels = 1;           
                boolean signed = true;          
                boolean bigEndian = false;       
                return new AudioFormat(
                                  sampleRate,
                                  sampleSizeInBits,
                                  channels,
                                  signed,
                                  bigEndian);
              }

                public void captureAudio() {
            try {

                Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
                System.out.println("Available mixers:");
                for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
                    System.out.println(mixerInfo[cnt].getName());
                }
                audioFormat = getAudioFormat();

                DataLine.Info dataLineInfo = new DataLine.Info(
                        TargetDataLine.class, audioFormat);

                Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

                targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);

                targetDataLine.open(audioFormat);
                targetDataLine.start();

                Thread captureThread = new CaptureThread();
                captureThread.start();      
            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
        }

            class CaptureThread extends Thread {

            byte tempBuffer[] = new byte[10000];

            public void run() {         
                try {
                    while (true) {
                        int cnt = targetDataLine.read(tempBuffer, 0,
                                tempBuffer.length);
                        out.write(tempBuffer);              
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    System.exit(0);
                }
            }
        }


    }

   // And this is how I call the class using a button of course.


     try {
                sender sd =new sender();
            } catch(LineUnavailableException ex) {
                Logger.getLogger(server_frame.class.getName()).log(Level.SEVERE,null, ex);
            }

Edited 4 Years Ago by khalidshakar: correct

When you call anything from an actionPeformed the whole of Swing (including GUI updates) will wait until your actionPerformed returns. This is because it's all done on one thread (Swing is not thread-safe). You need your actionPerformed to start a new thread for this code so it can return immediately.

Edited 4 Years Ago by JamesCherrill

Thank you very much. is it in this way?If not, could you please show me how? because I am just a beginner in java and I don't know much about it.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;

public class senderThread implements Runnable{


    ServerSocket MyService;
    Socket clientSocket = null;
    BufferedInputStream input;
    TargetDataLine targetDataLine;

    BufferedOutputStream out;
    ByteArrayOutputStream byteArrayOutputStream;
    AudioFormat audioFormat;    
    SourceDataLine sourceDataLine;    
    byte tempBuffer[] = new byte[10000];

    /**
     * Creates a new instance of <code>senderThread</code>.
     */
    public void run() {

        try{

            sender();   

        }catch(Exception e){
            System.out.println("Can not run thread");
        }


    }

     public void sender() throws LineUnavailableException{


                try {
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo =  new DataLine.Info( SourceDataLine.class,audioFormat);
            sourceDataLine = (SourceDataLine)
            AudioSystem.getLine(dataLineInfo);
            sourceDataLine.open(audioFormat);
            sourceDataLine.start();
            MyService = new ServerSocket(5000);
            ////////////////////////////////////////////////
            ////////////////////////////////////////////////////
            clientSocket = MyService.accept();
            captureAudio();
            input = new BufferedInputStream(clientSocket.getInputStream()); 
            out=new BufferedOutputStream(clientSocket.getOutputStream());

            while(input.read(tempBuffer)!=-1){          
                sourceDataLine.write(tempBuffer,0,10000);
            }
        } catch (IOException e) {

            e.printStackTrace();
        }


    }

         private AudioFormat getAudioFormat(){
            float sampleRate = 8000.0F;       
            int sampleSizeInBits = 16;         
            int channels = 1;           
            boolean signed = true;          
            boolean bigEndian = false;       
            return new AudioFormat(
                              sampleRate,
                              sampleSizeInBits,
                              channels,
                              signed,
                              bigEndian);
          }

            public void captureAudio() {
        try {

            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            System.out.println("Available mixers:");
            for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
                System.out.println(mixerInfo[cnt].getName());
            }
            audioFormat = getAudioFormat();

            DataLine.Info dataLineInfo = new DataLine.Info(
                    TargetDataLine.class, audioFormat);

            Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

            targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);

            targetDataLine.open(audioFormat);
            targetDataLine.start();

            Thread captureThread = new CaptureThread();
            captureThread.start();      
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }

        class CaptureThread extends Thread {

        byte tempBuffer[] = new byte[10000];

        public void run() {         
            try {
                while (true) {
                    int cnt = targetDataLine.read(tempBuffer, 0,
                            tempBuffer.length);
                    out.write(tempBuffer);              
                }

            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
        }
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {


      Runnable runnable=new senderThread();
      Thread thread=new Thread(runnable);
      thread.start();

    }
}

Edited 4 Years Ago by khalidshakar: correction

after I press that button it causes the program GUI to stop responding

Where is the button that is pressed? and where is the GUI that stops?

//here is the GUI

package vc_server1;

import javax.sound.sampled.LineUnavailableException;
import vc_server1.sender;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class server_frame extends javax.swing.JFrame {


    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;

        static  Socket clientSocket2 = null;
    static  ServerSocket serverSocket2 = null;

    public static javax.swing.JLabel labelU[] = new javax.swing.JLabel[100];


    static Server s[] = new Server[1];
    static screenServer ss[] = new screenServer[1];


    public server_frame() {
        initComponents();
        // t_on.setVisible(true);
        // t_off.setVisible(false);

         t_on.setVisible(true);
         t_off.setVisible(true);

        try {
            InetAddress local = InetAddress.getLocalHost();
          hostName.setText(local.getHostName());  
          txt_IP.setText(local.getHostAddress());
        } catch (UnknownHostException ex) {
            Logger.getLogger(server_frame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")


    private void t_onActionPerformed(java.awt.event.ActionEvent evt) {                                     

        //////////////////////


        ///////////////////////

          try{
     // The default port & IP
    int port_number = Integer.parseInt(txt_port.getText());
        String ip = txt_IP.getText();

        serverSocket = new ServerSocket(port_number);
        serverSocket2 = new ServerSocket(port_number+1);

        (s[0] = new Server(serverSocket,s) ).start();
        (ss[0] = new screenServer(serverSocket2,ss) ).start();
        //hid_button();


    }
    catch (Exception e) {

        System.out.println(e);
                       }


   chatHistory.append("<You>: "+"/broadcasting\n");

        t_on.setEnabled(false);
        t_off.setEnabled(true);

    }                                    

    // Switch off button will close the socket
    private void t_offActionPerformed(java.awt.event.ActionEvent evt) {                                      

          try
        {

         Server.serverSocket.close();
         Server.serverSocket.close();

         screenServer.serverSocket2.close();
         screenServer.serverSocket2.close();
        // show_button();
        // System.exit(0);
        }
        catch(Exception e)
        {

        }

      sender.CaptureThread.interrupted();

        t_on.setEnabled(true);
        t_off.setEnabled(false);
    }                                     

    // About button
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        JOptionPane.showMessageDialog(this, " IT Project II\nKuala Lumpur Infrstructure Univercity College"
                                           +"\nKHALID AMEEN AHMED SHAKAR\nkhalidshakar@yahoo.com\n+60193704236 ");


    }                                        

    private void hostNameActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         


         String message;
        String newline="\n";

             message=  chatText.getText();//chatText.getText();
            chatHistory.append("<You>:"+message+newline);


        try{
             for(int i=0; i<=9; i++)
             {

           Server.t[i].bw.write(message);
            Server.t[i].bw.newLine();
            Server.t[i].bw.flush();

            }
        }catch(Exception m){
        m.printStackTrace();
        }
             this.chatText.setText("");
        // TODO add your handling code here:
    }                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    // TODO add your handling code here:

        JOptionPane.showMessageDialog(this, " To create a database follow these steps:"
                                           + "\n 1. Open wampserver and create database with the name 'student_login_info'"
                                           + "\n 2. Create table with the name 'table1' with two (2)fields"
                                           + "\n 3. Name of field1 is 'name' and field2 is 'id' "
                                           +"\nThank you");

}                                        

private void startBroadcastActionPerformed(java.awt.event.ActionEvent evt) {                                               
//here is the button that cause stopping 

    try {
            sender sd=new sender();
            sd.captureAudio();
        } catch (LineUnavailableException ex) {
            Logger.getLogger(server_frame.class.getName()).log(Level.SEVERE, null, ex);
        }

}                                              

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
System.exit(0);
    // TODO add your handling code here:
}                                        

    public static void printList(String name, int id)
    {

       labelU[id] = new javax.swing.JLabel();
       labelU[id].setText(" - "+name);
       labelU[id].setFont(new java.awt.Font("Tahoma", 1, 12)); 


       userList.add(labelU[id]);

       jScrollPane1.getVerticalScrollBar().setValue(10);
       jScrollPane1.getVerticalScrollBar().setValue(0);

    }

     javax.swing.JButton b[] = new  javax.swing.JButton[4];

    /*  private void hid_button()
    {
        t_on.setVisible(false);
        t_off.setVisible(true);

    }
    private void show_button()
    {
        t_on.setVisible(true);
        t_off.setVisible(false);
    }
*/
    /**
    * @param args the command line arguments
    */

          private void process()
    {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setSize(dim.width, dim.height-40);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
}

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

           //  new server_frame().setVisible(true);
                  new server_frame().process();



            }


        });

    }

    // Variables declaration - do not modify                     
    public static javax.swing.JTextArea chatHistory;
    public javax.swing.JTextArea chatText;
    private javax.swing.JTextField hostName;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    public static javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JButton startBroadcast;
    private javax.swing.JButton t_off;
    private javax.swing.JButton t_on;
    private javax.swing.JTextField txt_IP;
    private javax.swing.JTextField txt_port;
    public static javax.swing.JPanel userList;
    // End of variables declaration                   

}

after I press that button it causes the program GUI to stop

Where is the listener added to the button? Which button is being clicked that causes the GUI to stop?

The posted code has many compiler errors because of missing classes.

Can you make a small, complete program that compiles, executes and shows the problem.
Do NOT post all the project with hundreds of lines of code.

Edited 4 Years Ago by NormR1

Lines 184,185 these need to be run in a new thread - just like the revised version of the sender code that you posted. That way the actionPerformed will start the thread and immediately return, after which the GUI will be able to respond/update as usual

Thank you Mr.JamesCherrill I couldn't call the revised version of the sender code. I am getting an error which says can't fined symbol. Maybe I am just stupid about that.

Ok Mr.NormR1 thank you for your respond. this is a simple GUI with a button which clicked to run sender class(The first post).

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyGUI {

public static void main(String[] args) {

       new MyGUI();

          }

      public MyGUI(){
        JFrame jf=new JFrame();


        jf.setTitle("My frame");
        ;
        jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
        JButton jb = new JButton("Start Broadcast sound");
        jb.setSize(new Dimension(50,50));

         jb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
               try{


                sender s=new sender();
               }catch(Exception d){
                System.out.println("Error");
               }

            }
        });      


        jb.setMnemonic(KeyEvent.VK_B); 

        jf.add(jb);

        jf.setSize(500,300);
        jf.setVisible(true);
             }


}

Edited 4 Years Ago by khalidshakar: correction

No, I didn't mean call the revised sender code exactly as it is! The revised version starts a new thread and runs the new Sender() (etc) in that thread. You need to do the same thing in your actionPeformed. The revised code is a good template or example for how to do that.

Note that after clicking the button, the frame freezes , just such this happens to my server frame..

Edited 4 Years Ago by khalidshakar: correction

Finally ,I have done it, thank you very much Mr.JamesCherrill and Mr.NormR1 .

This question has already been answered. Start a new discussion instead.