Results 1 to 4 of 4
  1. #1
    terox13 is offline Member
    Join Date
    May 2008
    Posts
    6
    Rep Power
    0

    Default [SOLVED] Thread in GUI Problem

    Hi, I have just recently been teaching myself networking and threads in java and I have encountered a problem. I'm trying to make a server - client type chat room and I'm having trouble with a thread in the client code.
    Client Code:
    Java Code:
    //ChitChatClient
    
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class ChitChatClient extends JFrame implements Runnable, ActionListener {
    	
    //	Declares input/output variables	
    	static Socket clientSocket = null;  
    	static BufferedReader inFromServer = null;
            static DataOutputStream outToServer = null;
    	static String input = "", output = "", strPort = "", username = "", numIp = "";
    	static int numPort = 0;
    	
    //	Declares the gui objects
    	static JTextArea inputBox, displayBox, userList;
    	static JButton send, connect;
    	static JTextField ip, port, txtUsername;
    	JLabel lblIp, lblPort, lblUsername;
    
    	public ChitChatClient() {
    		super("ChitChatClient 2.0");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLayout(null);
    		//frame.getContentPane().setBackground(Color.blue);
    		setBounds(400, 100, 600, 600);
    		setResizable(false);
    		
    //		Make the inputBox
    		inputBox = new JTextArea();
    		inputBox.setLineWrap(true);
    		inputBox.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    		JScrollPane inputScroll = new JScrollPane(inputBox);
    		inputScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		inputScroll.setBounds(20, 450, 440, 100);
    
    //		Makes the displayBox
    		displayBox = new JTextArea("");
    		displayBox.setBounds(20, 50, 350, 375);
    		displayBox.setLineWrap(true);
    		displayBox.setEditable(false);
    		JScrollPane displayScroll = new JScrollPane(displayBox);
    		displayScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		displayScroll.setBounds(20, 50, 350, 375);
    		
    //		Makes the button send
    		send = new JButton("Send");
    		send.setEnabled(false);
    		send.setBounds(480, 490, 100, 25);
    		send.addActionListener(this);
    		
    //		Makes the connect button
    		connect = new JButton("Connect");
    		connect.setBounds(20, 10, 100, 25);
    		connect.addActionListener(this);
    		
    //		Makes lblIp label
    		lblIp = new JLabel("Ip address:");
    		lblIp.setBounds(130, 10, 75, 25);
    		
    //		Makes the lblPort label
    		lblPort = new JLabel("Port:");
    		lblPort.setBounds(310, 10, 50, 25);
    		
    //		Makes the lblUsername label
    		lblUsername = new JLabel("Username:");
    		lblUsername.setBounds(400, 10, 75,25);
    		
    //		Makes the ip JtextField
    		ip = new JTextField();
    		ip.setBounds(200, 15, 95, 20);
    		
    //		Makes the port JTextField
    		port = new JTextField();
    		port.setBounds(345, 15, 40, 20);
    		
    //		Makes the txtUsername JTextField
    		txtUsername = new JTextField();
    		txtUsername.setBounds(470, 15, 100, 20);
    		
    //		Add objects to frame
    		add(inputScroll);
    		add(displayScroll);
    		add(send);
    		add(connect);
    		add(lblIp);
    		add(lblPort);
    		add(ip);
    		add(port);
    		add(lblUsername);
    		add(txtUsername);
    		
    		repaint();
    	}
    	
    	public void actionPerformed(ActionEvent e) { 
    		if(e.getSource() == send) {
    			try {
    				output = inputBox.getText();
    				outToServer.writeBytes(username + ": " + output + "\n");
    				inputBox.setText("");
    			}
    			catch(IOException er) {}
    		}
    		else if(e.getSource() == connect) {
    //			Disable connection controls		
    			connect.setEnabled(false);
    			ip.setEnabled(false);
    			port.setEnabled(false);
    			txtUsername.setEnabled(false);
    				
    //		Assign connection variables
    			numIp = ip.getText();
    			strPort = port.getText();
    			numPort = Integer.parseInt(strPort);
    			username = txtUsername.getText();
    			
    //		Creates socket to connect to the server
    			try {
    				displayBox.append("\nConnecting to server...");
    				clientSocket = new Socket(numIp, numPort);
    			}
    			catch(UnknownHostException er) {
    				displayBox.append("\nCan't connect to server.");
    //				Enable connection controls		
    				connect.setEnabled(true);
    				ip.setEnabled(true);
    				port.setEnabled(true);
    				txtUsername.setEnabled(true);			}
    			catch(IOException er) {
    				displayBox.append("\nCan't connect to server.");
    //				Enable connection controls		
    				connect.setEnabled(true);
    				ip.setEnabled(true);
    				port.setEnabled(true);
    				txtUsername.setEnabled(true);
    			}
    //			Creates an input and output streams	
    			try {
    //				Creates input from the server	
    				inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));	
    //				Creates output from the server
    				outToServer = new DataOutputStream(clientSocket.getOutputStream());
    			}
    			catch (IOException er) {
    					System.out.println(er);
    			}
    
    			[COLOR="Blue"](new Thread(new ChitChatClient())).start();[/COLOR]
    		}
        }
    	
    	public static void main(String args[]) throws Exception {
    		JFrame frame = new ChitChatClient();
    		frame.setVisible(true);
    
    		displayBox.append("Welcome to ChitChatClient Version 2.0");
    		
    //		Reads the ip text file
    		File file = new File("ClientConfig.txt");
    		if (file.exists()) {
    			// Create a BufferedReader from the file
    			BufferedReader inFile = new BufferedReader(new java.io.FileReader(file));
    //			Reads the ip
    			numIp = inFile.readLine();
    			strPort = inFile.readLine();
    			username = inFile.readLine();
    			
    //			 Close the buffered reader input stream attached to the file
    			inFile.close();
    			
    //			Put the variables in the JTextFields
    			ip.setText(numIp);
    			port.setText(strPort);
    			txtUsername.setText(username);
    		}
    			
    	}
    	
    	public void run() {
    		try {
    			displayBox.append("\nServer Connected");
    			send.setEnabled(true);
    			outToServer.writeBytes("User '" + username + "' has joined.\n");
    			while(true) {
    				input = inFromServer.readLine();
    				displayBox.append("\n" + input);
    				Toolkit.getDefaultToolkit().beep();
    			}
    		}
    		catch(IOException er) {
    			System.out.println(er);
    		}
    		finally {
    			try {
    				clientSocket.close ();
    				inFromServer.close();
    				outToServer.close();
    			} 
    			catch (IOException ex) {
    				ex.printStackTrace ();
    			}
    		}	
    	}
    }
    The GUI is a JFrame and is made in the constructor method. What I want to happen is when the user clicks the connect JButton, they connect to the server. I'm assuming I need a thread to handle everything coming in from the server so the user can interact with the GUI at the same time. I start the thread in the actionPerformed method (highlighted in blue). The text "Connecting to server..." shows up but when it gets to the thread it just stops and doesn't implement any of the code in the run() method. I had this program working without the GUI and is basically the same code. The only thing different that I can think of is I started the thread from the main method and not the actionPerformed method. Any help would be greatly appreciated.

  2. #2
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    7

    Default

    Don't do anything time consuming on the GUI thread. Start a new thread for connection. Don't update the GUI from other threads but the GUI thread. Use invokeLater()
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  3. #3
    terox13 is offline Member
    Join Date
    May 2008
    Posts
    6
    Rep Power
    0

    Default

    I got it to work, thank you. I just made a new class that extended thread and called that.

  4. #4
    gogoc is offline Member
    Join Date
    May 2008
    Posts
    21
    Rep Power
    0

    Default

    you can also use "Display.getCurrent().asyncExec(runnable)" to get ur thing done

Similar Threads

  1. Animation Delay - Thread problem
    By wererabit in forum Advanced Java
    Replies: 3
    Last Post: 04-10-2009, 11:35 PM
  2. [SOLVED] HELP! Thread Problem
    By nvidia in forum NetBeans
    Replies: 2
    Last Post: 05-24-2008, 05:56 AM
  3. Problem using thread +rmi in my homework
    By IbrahimAbbas in forum Threads and Synchronization
    Replies: 10
    Last Post: 04-14-2008, 10:24 PM
  4. Replies: 0
    Last Post: 01-28-2008, 08:02 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
  •