Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2006

Tip: Looking for answers? Try searching our database.

Threads and Gui

Thread view: 
James - 08 Apr 2006 10:20 GMT
How can I have the run method append to jTextArea1?

/*
* Chat.java
*
* Created on 7 April 2006, 17:53
*/
import java.io.*;
import java.net.*;
import java.util.*;
/**
*
* @author  Glen
*/
public class Chat extends javax.swing.JFrame {

   /** Creates new form Chat */
   public Chat(Socket socket) {
       this.socket=socket;
       try
       {
          out = new PrintStream(socket.getOutputStream());
       }
       catch(Exception e){}
       initComponents();
   }

   /** 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.
    */
   // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
   private void initComponents() {
       jScrollPane1 = new javax.swing.JScrollPane();
       jTextArea1 = new javax.swing.JTextArea();
       jPanel1 = new javax.swing.JPanel();
       jTextField1 = new javax.swing.JTextField();
       jButton1 = new javax.swing.JButton();

       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
       setTitle("Chat");
       jTextArea1.setColumns(20);
       jTextArea1.setRows(5);
       jTextArea1.setFocusable(false);
       jScrollPane1.setViewportView(jTextArea1);

       getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

       jPanel1.setLayout(new java.awt.GridLayout());

       jPanel1.add(jTextField1);

       jButton1.setText("Send");
       jButton1.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
               jButton1ActionPerformed(evt);
           }
       });

       jPanel1.add(jButton1);

       getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

       pack();
   }// </editor-fold>

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

     //out = new PrintStream(socket.getOutputStream());
     String temp=jTextField1.getText();
     jTextArea1.append("You: "+temp+"\n");
     out.println(temp);
     out.flush();
   }

   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) {
     try {
        Socket socket = new Socket("localhost", PORTNUM);
       Chat app= new Chat(socket);
           app.setSize(500, 400);
           app.setLocation(100, 100);
           app.setVisible(true);

        readThread t=new readThread(socket);
        t.start();

     //out.close();       socket.close();
   }
   catch (IOException e) {      System.err.println(e);     }

       }

   private Socket socket;
   private PrintStream out;
   private static final int PORTNUM = 44130;
   // Variables declaration - do not modify
   private javax.swing.JButton jButton1;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JTextArea jTextArea1;
   private javax.swing.JTextField jTextField1;
   // End of variables declaration
}

class readThread extends Thread
{
  private Socket socket;
  private DataInputStream in;

  public readThread(Socket soc)
  {
     socket=soc;
  }

  public void run()
  {
    try
    {
         in = new DataInputStream(socket.getInputStream());
         String inStr;
         while(true)
         {
            inStr = in.readLine();
            System.out.println(inStr);
            if(inStr.compareTo("")==0) break;
          }
          in.close();
     }
   catch (IOException e) {      System.err.println(e);     }
  }
}
Thomas Hawtin - 08 Apr 2006 10:28 GMT
> How can I have the run method append to jTextArea1?

Just pass the text area in through the "readThread" class' constructor.

In this case you are lucky. Unusually, JTextArea.append is thread-safe.
In most other cases you would need another Runnable inside your run
method. Something like

    String line = in.readLine();
    if (line == null) {
        break;
    }
    java.awt.EventQueue.invokeLater( // unnecessary in this case
        new Runnable() { public void run() {
                textArea.append(line);
        }}
    );

Not relevant to the question but I would suggest: Ignore the J for
variable names of Swing components. Don't just add meaningless number
suffixes to variable names. Stick to the code conventions - always use
initial caps for class names. Don't use inheritance where you don't have
to - JFrame and Thread should rarely be extended.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.