Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 05-10-2008, 08:33 AM
Member
 
Join Date: May 2008
Posts: 6
terox13 is on a distinguished road
[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:
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); } (new Thread(new ChitChatClient())).start(); } } 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.
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 05-11-2008, 03:34 AM
danielstoner's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Canada
Posts: 183
danielstoner is on a distinguished road
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 @ [
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
]
Language is froth on the surface of thought
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 05-11-2008, 04:36 AM
Member
 
Join Date: May 2008
Posts: 6
terox13 is on a distinguished road
I got it to work, thank you. I just made a new class that extended thread and called that.
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 05-27-2008, 09:32 PM
Member
 
Join Date: May 2008
Posts: 21
gogoc is on a distinguished road
you can also use "Display.getCurrent().asyncExec(runnable)" to get ur thing done
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] HELP! Thread Problem nvidia NetBeans 4 05-24-2008 05:57 AM
Animation Delay - Thread problem wererabit Advanced Java 1 04-17-2008 09:41 AM
Problem using thread +rmi in my homework IbrahimAbbas Threads and Synchronization 10 04-14-2008 10:24 PM
If JNI thread call the java object in another thread, it will crash. skaterxu Advanced Java 0 01-28-2008 08:02 AM
Creating a Thread (extending Java Thread Class) JavaForums Java Blogs 0 12-19-2007 10:31 AM


All times are GMT +3. The time now is 09:28 AM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org