Start Stop Button


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 7 of 7

Thread: Start Stop Button

  1. #1
    Join Date
    Nov 2005
    Posts
    17

    Start Stop Button

    I have a applet that connects to a server via a socket, recieves random data, and display that data. So far the applet can stop the data from being recieved by closing the socket using the stop button. The socket can then be re-open again and start recieving data if the start button is pressed. However after I have pressed the start button and reconnected the socket, I can not stop or re-start the socket as the buttons freeze up. I think this is something to do with the thread or something, but I very new to Java and am a bit confused about this.
    Code:
    /**
     *Applet Client Program
     * @author  Sam Boothman
     * @version 1.3, Nov 2005
     */
    
    import java.io.*;									//Imports all neccessary class files
    import java.net.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*; 
    
    public class Applet1_3 extends Applet implements ActionListener, Runnable 
    {    
    	private static final String HOST = "10.3.1.96";	//Creates a private string called "HOST" and assigns a IP address
    	private static final int PORT = 9999;        	//Creates a private string called "PORT" and assigns a port number
    	TextField[] fields = new TextField[10];    		//Creates a textfield with an array of ten elements
    	Button stopButton;    							//Creates a button called "stopButton"
    	Button startButton;            					//Creates a button called "startButton"
    	boolean stop,start;        					//Assigns "stop" as a boolean variable
    	
    	public void init() 								//Initialisation method
    	{        
    		setSize(200,320);                           //Sets Applet resolution to specified size (x,y)
    		setBackground(Color.gray);                  //Sets background color to specified color           
    		for (int i = 0; i < fields.length; i++) 	//Sets initialization; termination; increment of the FOR loop
    		{            
    			add(new Label("Reading " + (i + 1)));   //Adds a new label to the applet with value "i" to indicate which reading number it is         
    			fields[i] = new TextField("", 6);       //Creates a 10 TextFields and assigns it a number using "i" in the FOR loop    
    			add(fields[i]);        					//Adds a 10 TextFields to the applet with value "i" to identify the TextField 
    		}                
    		startButton = new Button("START");         	//Creates a button called "startButton"
    		stopButton = new Button("STOP");           	//Creates a button called "stopButton" 
    		
    		add(startButton);          				   	//Adds "startButton" to the applet	
    		add(stopButton);                  		   	//Adds "stopButton" to the applet	
    		
    		stopButton.addActionListener(this);        	//Adds a ActionListener to the stopButton
    		startButton.addActionListener(this);       	//Adds a ActionListener to the startButton
    		new Thread(this).start();  				   	//Creates and starts a default thread
    		//startButton.addActionListener(this);       	//Adds a ActionListener to the startButton
    		//new Thread(this).start();				   	//Creates and starts a default thread
    	}        
    	
    	public void run() 								//Declares "run" method
    	{            
    		Socket clientSocket = null;        			//Declares "clientSocket" as a Socket
    		BufferedReader is = null;        			//Declares "is" as a BufferedReader
    		try 
    		{            
    			clientSocket = new Socket(HOST, PORT);	//Creates a socket called clientSocket and set parameters as "HOST" & "PORT"                     
    			is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));	//Creates a BufferedReader called "is" and gets the input stream from clientSocket               
    			int i = 0;            
    			while (!stop) 								//While loop exits if stop equals true
    			{                
    				String responseLine = is.readLine();	//A srting is created called "responseLine" has data passed to it from "is.readLine"                
    				if (responseLine == null) break;  		//If responseLine has no data, then the while loop breaks              
    				if (responseLine.indexOf("ok") != -1) break;                
    				int index = i++ % 10;  					//Index increments untill it reaches 10              
    				fields[index].setText(responseLine);    //Ten fields are drawn with a different responseLine value for each                       
    			}        
    		} 
    		catch (Exception e) 						//Catch an exception
    		{            
    			e.printStackTrace();        
    		}        
    		
    		finally 
    		{            
    			try 
    			{ 
    				if (clientSocket != null) clientSocket.close();	//If "clientSocket" is free of data, then close
    			} 
    			catch (Exception e) 					//Catch an exception
    			{ e.printStackTrace(); 
    			}            
    			try { 
    				if (is != null) is.close(); 		//If "is" is free of data, then close 
    				} 
    			catch (Exception e) 					//Catch an exception
    			{ 
    				e.printStackTrace(); 
    			}        
    		}    
    	}
    	public void actionPerformed(ActionEvent evt)  	//Declares "actionPerformed" methods with parameters
    	{        
    		if (evt.getSource() == stopButton) stop = true;		//If "stopButton" is pressed assign a true value to variable "stop"       
    		
    		if (evt.getSource()== startButton) stop = false;	//If "startButton" is pressed assign a false value to variable "stop"
    		{
    			//init();								//Call "init" method
    			run();									//Call "run" method
    			
    		}
    		
    	}  
    }

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    Yeh, essentially, the call to get the data is "blocking" the handeling of the event queue. So, what you are going to have to do is make a thread and when you click the "start" button, you run this thread which will read the data and do whatever you want to do. If the "stop" button is clicked, you kill the thread (which should close the socket). This being said, swing has some major annoyances when you used threads to do updates of gui components. If you start getting weird synchronization problems, you should check out SwingWorker classes, which are available in various places (just search google).

    Hope this helps.
    ~evlich

  3. #3
    Join Date
    Oct 2005
    Posts
    107
    to safely update gui from another thread try this method out...

    public void updateView(final String responseLine, final int index){
    Runnable updateAComponent = new Runnable() {
    public void run() { fields[index].setText(responseLine)}
    };
    SwingUtilities.invokeLater(updateAComponent);

    }

    where fields needs to be declared final to be used in anonymous class
    Last edited by Joe Beam; 11-29-2005 at 01:10 AM.

  4. #4
    Join Date
    Nov 2005
    Posts
    17
    cheers, I will give it a try

  5. #5
    Join Date
    Nov 2005
    Posts
    17
    Ok I have tried that, not sure if I have done it right, but I have put the connection and getting the data in a thread. But when I run the program I am getting a NullPointerException on getting the HOST number, and I would imagine the rest of the parameters like that. Do I have to pass an agument or values from to the thread to allow the thread access to the main classes variables, like HOSTS, PORT, stop and fields.
    Below is the code. I am quite new to java, so this has been put together on the info I found on the net. It what I think made sense to do, but could be completly wrong.

    Code:
    /**
     *Applet Client Program
     * @author  Sam Boothman
     * @version 1.3, Nov 2005
     */
    
    import java.io.*;									
    import java.net.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*; 
    import javax.swing.*;
    
    class ConnectionThread1 extends Thread
    {
    	public Applet1_5 Applet = null;
        public ConnectionThread1(Applet1_5 arg){
        	Applet=arg;
        }
        
        public void run() 
        {
        	Socket clientSocket = null;        			
    		BufferedReader is = null;        			
    		try 
    		{  
    			clientSocket = new Socket(Applet.HOST, Applet.PORT);	
    			is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));	 
    			               
    			int i = 0;            
    			while (!Applet.stop) 								
    			{                
    				String responseLine = is.readLine();	
    				if (responseLine == null) break;  		             
    				if (responseLine.indexOf("ok") != -1) break;                
    				int index = i++ % 10;  					           
    				Applet.fields[index].setText(responseLine);    
    			}        
    		} 
    		catch (Exception e) 						
    		{            
    			e.printStackTrace();        
    		}        
    		
    		finally 
    		{            
    			try 
    			{ 
    				if (clientSocket != null) clientSocket.close();	//If "clientSocket" is free of data, then close
    			} 
    			catch (Exception e) 					
    			{ 
    				e.printStackTrace(); 
    			}            
    			try { 
    				if (is != null) is.close(); 		 
    				} 
    			catch (Exception e) 					
    			{ 
    				e.printStackTrace(); 
    			}        
    		}
        }
    }
    /************************************************************************************************/
    /************************************************************************************************/
    public class Applet1_5 extends Applet implements ActionListener, Runnable 
    {    
    	/*private static final*/ String HOST = "10.3.1.96";	
    	/*private static final*/ int PORT = 9999;        	
    	private static final Applet1_5 Applet = null;
    	TextField[] fields = new TextField[10];    		
    	Button stopButton;    							
    	Button startButton;            					
    	boolean stop,start;        					
    	
    	public void init() 								
    	{        
    		setSize(200,320);                           
    		setBackground(Color.gray);                         
    		for (int i = 0; i < fields.length; i++) 	
    		{            
    			add(new Label("Reading " + (i + 1)));            
    			fields[i] = new TextField("", 6);      
    			add(fields[i]);        					
    		}                
    		startButton = new Button("START");         	
    		stopButton = new Button("STOP");           	
    		
    		add(startButton);          				   	
    		add(stopButton);                  		   	
    		
    		stopButton.addActionListener(this);        	
    		startButton.addActionListener(this);       	
    		new Thread(this).start();  	
    			
    		
    		
    	}  
    	
    	public void run() 								
    	{   
    		ConnectionThread1 thread = new ConnectionThread1(Applet);
    	    thread.start();	
    		/*Socket clientSocket = null;        			
    		BufferedReader is = null;        			
    		try 
    		{            
    			clientSocket = new Socket(HOST, PORT);	
    			is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));	                       
    		} 
    		catch (Exception e) 						
    		{            
    			e.printStackTrace();        
    		}        
    		
    		finally 
    		{            
    			try 
    			{ 
    				if (clientSocket != null) clientSocket.close();	
    			} 
    			catch (Exception e) 					
    			{ 
    				e.printStackTrace(); 
    			}            
    			try { 
    				if (is != null) is.close(); 		
    				} 
    			catch (Exception e) 					
    			{ 
    				e.printStackTrace(); 
    			}        
    		}*/
    	}
    	
    	
    	public void actionPerformed(ActionEvent evt)  	
    	{        
    		if (evt.getSource() == stopButton) stop = true;	
    		{
    			
    		}
    		
    		if (evt.getSource()== startButton) stop = false;	
    		{
    			ConnectionThread1 thread = new ConnectionThread1(Applet);
    		    thread.start();								
    			
    		}
    		
    	}  
    }

  6. #6
    Join Date
    Oct 2005
    Posts
    107
    if you made HOST and PORT public variables then you could access them like
    Applet.HOST or Applet.PORT

    also you are passing in your null reference here...

    private static final Applet1_5 Applet = null; //this field is not needed use 'this' keyword
    ...
    ...
    ConnectionThread1 thread = new ConnectionThread1(Applet);

    I think what you really want is to use the 'this' keyword like...
    ConnectionThread1 thread = new ConnectionThread1(this);

  7. #7
    Join Date
    Nov 2005
    Posts
    17
    cheer Joe Beam, that did the trick. Thanks to eveyone else as well for your help, its a lot easier to understand and learn java when you got people like you guys to to help.
    Regards
    Sam

Similar Threads

  1. Replies: 2
    Last Post: 05-16-2005, 11:22 AM
  2. button listener not working
    By DrunkinP in forum Java
    Replies: 0
    Last Post: 03-31-2005, 10:36 AM
  3. Start / stop Dialup server for win 95/98 programatically
    By Bogdan Zamfir in forum VB Classic
    Replies: 0
    Last Post: 05-10-2001, 07:54 PM
  4. Start / stop Dialup server for win 95/98 programatically
    By Bogdan Zamfir in forum VB Classic
    Replies: 0
    Last Post: 05-10-2001, 07:54 PM
  5. Re: Creating a windows Start like button
    By Mike in forum VB Classic
    Replies: 0
    Last Post: 03-16-2000, 07:05 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center