10 Replies - 1525 Views - Last Post: 29 February 2012 - 02:41 PM Rate Topic: -----

#1 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

I am having a problem with my GUI not appending the String

Posted 28 February 2012 - 10:02 PM

When I run this GUI I can't get it to put the servers response to my GUI textfield. Anyone see any problems. I think it is somewhere in here
    public void run() {
        String responseLine;
	
	 // Keep reading from the socket until we receive the "logout" from the server,
	 // once we get that then we break.
	try{ 
	    while ((responseLine = is.readLine()) != null) {
		System.out.println(responseLine);
                serverInput.append(responseLine);
		if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }//END IF
	    }
            //closed = true;
            is.close();
            os.close();
            clientSocket.close();
	} catch (IOException e) {
	    System.err.println("IOException:  " + e);
	}
    }//END run()

but if you don't think so I'll post the rest of the class. Any tips Help! Thanks guys!



package ClientGUI;




import java.io.*;
import java.net.*;
import java.util.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author Logan
 */
public class Client_UI extends javax.swing.JFrame  implements Runnable {
    private static InetAddress host;
    private static final int PORT = 16920;
    
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;

    /**
     * Creates new form Client_UI
     */
    public Client_UI() {
        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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        userTextInput = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        serverInput = new javax.swing.JTextArea();
        messageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Room");

        sendButton.setBackground(new java.awt.Color(204, 204, 204));
        sendButton.setText("Send");
        sendButton.setOpaque(false);
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        serverInput.setColumns(20);
        serverInput.setEditable(false);
        serverInput.setLineWrap(true);
        serverInput.setRows(5);
        jScrollPane1.setViewportView(serverInput);

        messageLabel.setText("Message");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(messageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        String usersInput;
        usersInput = userTextInput.getText();
        os.println(usersInput);
        userTextInput.setText("");
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Client_UI().setVisible(true);
            }//END RUN
        });
        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("\nHost ID not found!\n");
            System.exit(1);
        }
        chat();
        
    }//END MAIN
    
    
    private static void chat() {
        Socket socket = null;
        try {
            clientSocket = new Socket(host, PORT);
            inputLine = new BufferedReader(new InputStreamReader(System.in));
            
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.out.println("Couldn't Connect To The Host!");
            } catch (IOException e) {
            System.out.println("Couldn't get the I/O going!");
            }


                if(clientSocket != null && os != null && is != null) {
                //try {
                        //String message, response, name;

                        new Thread(new Client_UI()).start();
 
                }//END IF
        }//End chat();
 
    public void run() {
        String responseLine;
	
	 // Keep reading from the socket until we receive the "logout" from the server,
	 // once we get that then we break.
	try{ 
	    while ((responseLine = is.readLine()) != null) {
		System.out.println(responseLine);
                serverInput.append(responseLine);
		if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }//END IF
	    }
            //closed = true;
            is.close();
            os.close();
            clientSocket.close();
	} catch (IOException e) {
	    System.err.println("IOException:  " + e);
	}
    }//END run()
    
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextArea serverInput;
    private javax.swing.JTextField userTextInput;
    // End of variables declaration
}



Is This A Good Question/Topic? 0
  • +

Replies To: I am having a problem with my GUI not appending the String

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,908
  • Joined: 06-March 08

Re: I am having a problem with my GUI not appending the String

Posted 28 February 2012 - 10:14 PM

Updating Swing component into a Thread can bring unexpected results.
Swing is not Thread safe.

Extend your paint(Graphics g) method and put a println() into it to see if the GUI is refresh

But I bet that the Thread that repaint is the same as the one where your thread run
So any repaint won't be done until you exit your thread run()...
Was This Post Helpful? 0
  • +
  • -

#3 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

Re: I am having a problem with my GUI not appending the String

Posted 28 February 2012 - 10:31 PM

pbl where do you see a paint(Graphics g) method? I dont have one in my code.

This post has been edited by Sasquatch3o3: 28 February 2012 - 10:40 PM

Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,992
  • Joined: 20-September 08

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 02:22 AM

In place of

Quote

serverInput.append(responseLine);


try

java.awt.EventQueue.invokeLater(new GuiUpdater(responseLine));


and include the following inner class in your code

    private class GuiUpdater implements Runnable {
	private String displayString;

        public GuiUpdater(String displayString) {
            this.displayString = displayString;
        }

        public void run() {
            serverInput.append(displayString);
        }
    }


Was This Post Helpful? 0
  • +
  • -

#5 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 10:29 AM

g00se Thanks for the effort I tried that and still I got nothing to show up in my GUI textarea.
But sometimes when i run my GUI i get this error message:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.plaf.nimbus.NimbusStyle.validate(NimbusStyle.java:298)
at javax.swing.plaf.nimbus.NimbusStyle.getValues(NimbusStyle.java:806)
at javax.swing.plaf.nimbus.NimbusStyle.getInsets(NimbusStyle.java:485)
at javax.swing.plaf.synth.SynthStyle.installDefaults(SynthStyle.java:913)
at javax.swing.plaf.synth.SynthLookAndFeel.updateStyle(SynthLookAndFeel.java:258)
at javax.swing.plaf.synth.SynthPanelUI.updateStyle(SynthPanelUI.java:117)
at javax.swing.plaf.synth.SynthPanelUI.installDefaults(SynthPanelUI.java:100)
at javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:56)
at javax.swing.plaf.synth.SynthPanelUI.installUI(SynthPanelUI.java:62)
at javax.swing.JComponent.setUI(JComponent.java:664)
at javax.swing.JPanel.setUI(JPanel.java:153)
at javax.swing.JPanel.updateUI(JPanel.java:126)
at javax.swing.JPanel.<init>(JPanel.java:86)
at javax.swing.JPanel.<init>(JPanel.java:109)
at javax.swing.JPanel.<init>(JPanel.java:117)
at javax.swing.JRootPane.createGlassPane(JRootPane.java:545)
at javax.swing.JRootPane.<init>(JRootPane.java:365)
at javax.swing.JFrame.createRootPane(JFrame.java:277)
at javax.swing.JFrame.frameInit(JFrame.java:258)
at javax.swing.JFrame.<init>(JFrame.java:181)
at ClientGUI.Client_UI.<init>(Client_UI.java:33)
at ClientGUI.Client_UI.chat(Client_UI.java:181)
at ClientGUI.Client_UI.main(Client_UI.java:159)

maybe you guys would know anything here to fix.
Client_UI.java:33 is pointing to this line in my code
   ----> public Client_UI() {
        initComponents();
    }


Client_UI.java:181 is pointing to this line in my code
new Thread(new Client_UI()).start();


Client_UI.java:159 is pointing to this line in my code
chat();


once again here is the whole code just for a reference sake.
import java.io.*;
import java.net.*;
import java.util.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author Logan
 */
public class Client_UI extends javax.swing.JFrame  implements Runnable {
    private static InetAddress host;
    private static final int PORT = 16920;
    
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;

    /**
     * Creates new form Client_UI
     */
    public Client_UI() {
        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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        userTextInput = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        serverInput = new javax.swing.JTextArea();
        messageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Room");

        sendButton.setBackground(new java.awt.Color(204, 204, 204));
        sendButton.setText("Send");
        sendButton.setOpaque(false);
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        serverInput.setColumns(20);
        serverInput.setLineWrap(true);
        serverInput.setRows(5);
        jScrollPane1.setViewportView(serverInput);

        messageLabel.setText("Message");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(messageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        String usersInput;
        usersInput = userTextInput.getText();
        os.println(usersInput);
        userTextInput.setText("");
        serverInput.append("Sending Message...");
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Client_UI().setVisible(true);
            }//END RUN
        });
        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("\nHost ID not found!\n");
            System.exit(1);
        }
        chat();
        
    }//END MAIN
    
    
    private static void chat() {
        Socket socket = null;
        try {
            clientSocket = new Socket(host, PORT);
            inputLine = new BufferedReader(new InputStreamReader(System.in));
            
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.out.println("Couldn't Connect To The Host!");
            } catch (IOException e) {
            System.out.println("Couldn't get the I/O going!");
            }


                if(clientSocket != null && os != null && is != null) {
                    
                    new Thread(new Client_UI()).start();
 
                }//END IF
        }//End chat();
    
   
    public void run() {
        String responseLine;
	
	 // Keep reading from the socket until we receive the "logout" from the server,
	 // once we get that then we break.
	try{ 
	    while ((responseLine = is.readLine()) != null) {
		System.out.println(responseLine);
                serverInput.append(responseLine + "\n");
		if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }//END IF
	    }
            //closed = true;
            is.close();
            os.close();
            clientSocket.close();
	} catch (IOException e) {
	    System.err.println("IOException:  " + e);
	}
    }//END run()
    
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextArea serverInput;
    private javax.swing.JTextField userTextInput;
    // End of variables declaration
}


Was This Post Helpful? 0
  • +
  • -

#6 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,992
  • Joined: 20-September 08

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 11:02 AM

Quote

But sometimes when i run my GUI i get this error message:
Exception in thread "main" java.lang.NullPointerException


That's a whole other ball game and looks to be related to the LAF you're using
Was This Post Helpful? 0
  • +
  • -

#7 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 11:30 AM

View Postg00se, on 29 February 2012 - 11:02 AM, said:

Quote

But sometimes when i run my GUI i get this error message:
Exception in thread "main" java.lang.NullPointerException


That's a whole other ball game and looks to be related to the LAF you're using



I just used the Built in GUI maker in NetBeans, I didn't do anything to the LAF coded part, netbeans automatically generated that part. So, can I just delete that part out of my code...

This post has been edited by Sasquatch3o3: 29 February 2012 - 11:32 AM

Was This Post Helpful? 0
  • +
  • -

#8 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 12:00 PM

ok So I made my textarea a static variable and then threw it in my chat() method and now it is throwing this error:

Exception in thread "main" java.lang.NullPointerException
at ClientGUI.Client_UI.chat(Client_UI.java:190)
at ClientGUI.Client_UI.main(Client_UI.java:160)

Client_UI.java:190 is referring to this line of code:
serverInput.append(responseLine);


again here is a reference to my most recent changed class

import java.io.*;
import java.net.*;
import java.util.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author Logan
 */
public class Client_UI extends javax.swing.JFrame {
    private static InetAddress host;
    private static final int PORT = 16920;
    
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;

    /**
     * Creates new form Client_UI
     */
    public Client_UI() {
        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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        userTextInput = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        serverInput = new javax.swing.JTextArea();
        messageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Room");

        sendButton.setBackground(new java.awt.Color(204, 204, 204));
        sendButton.setText("Send");
        sendButton.setOpaque(false);
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        serverInput.setBackground(new java.awt.Color(0, 204, 204));
        serverInput.setColumns(20);
        serverInput.setEditable(false);
        serverInput.setLineWrap(true);
        serverInput.setRows(5);
        jScrollPane1.setViewportView(serverInput);

        messageLabel.setText("Message");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userTextInput, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(messageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        String usersInput;
        usersInput = userTextInput.getText();
        os.println(usersInput);
        userTextInput.setText("");
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Client_UI().setVisible(true);
            }//END RUN
        });
        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("\nHost ID not found!\n");
            System.exit(1);
        }
        chat();
        
    }//END MAIN
    
    
    private static void chat() {
        Socket socket = null;
        try {
            clientSocket = new Socket(host, PORT);
            inputLine = new BufferedReader(new InputStreamReader(System.in));
            
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.out.println("Couldn't Connect To The Host!");
            } catch (IOException e) {
            System.out.println("Couldn't get the I/O going!");
            }


                if(clientSocket != null && os != null && is != null) {
                    
                    //new Thread(new Client_UI()).start();
                    String responseLine;
	
                    // Keep reading from the socket until we receive the "logout" from the server,
                    // once we get that then we break.
                    try{ 
                        while ((responseLine = is.readLine()) != null) {
                            System.out.println(responseLine);
                            serverInput.append(responseLine);
                            if (responseLine.indexOf("*** Bye") != -1) {
                                break;
                            }//END IF
                        }
                        //closed = true;
                        is.close();
                        os.close();
                        clientSocket.close();
                    } catch (IOException e) {
                        System.err.println("IOException:  " + e);
                    }
 
                }//END IF
        }//End chat();
    
   /*
    public void run() {
        String responseLine;
	
	 // Keep reading from the socket until we receive the "logout" from the server,
	 // once we get that then we break.
	try{ 
	    while ((responseLine = is.readLine()) != null) {
		System.out.println(responseLine);
                serverInput.append(responseLine + "\n");
		if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }//END IF
	    }
            //closed = true;
            is.close();
            os.close();
            clientSocket.close();
	} catch (IOException e) {
	    System.err.println("IOException:  " + e);
	}
    }//END run()
    */
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton sendButton;
    private static javax.swing.JTextArea serverInput;
    private javax.swing.JTextField userTextInput;
    // End of variables declaration
}


Was This Post Helpful? 0
  • +
  • -

#9 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 12:10 PM

You have the serverInput variable instantiated in the initCOmponents() which is called in the constructor. However in the main method you never create a Client_UI object so that variable never gets instantiated.

It is very hard to read because you used NetBeans drag and Drop but I am fairly certain I did not see a Client_UI object made.
Was This Post Helpful? 1
  • +
  • -

#10 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,992
  • Joined: 20-September 08

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 12:34 PM

Quote

However in the main method you never create a Client_UI object


Actually the problem is kind of the reverse. You actually create your gui twice, the second time obscuring the first. The following is a rather hacked solution. You should smooth it out
import java.io.*;

import java.net.*;

import java.util.*;


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Logan
*/
public class Client_UI extends javax.swing.JFrame implements Runnable {
    private static InetAddress host;
    private static final int PORT = 16920;
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextArea serverInput;
    private javax.swing.JTextField userTextInput;

    /**
    * Creates new form Client_UI
    */
    public Client_UI() {
        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.
    */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        userTextInput = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        serverInput = new javax.swing.JTextArea();
	serverInput.append("HEY");
        messageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Room");

        sendButton.setBackground(new java.awt.Color(204, 204, 204));
        sendButton.setText("Send");
        sendButton.setOpaque(false);
        sendButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendButtonActionPerformed(evt);
                }
            });

        serverInput.setColumns(20);
        serverInput.setLineWrap(true);
        serverInput.setRows(5);
        jScrollPane1.setViewportView(serverInput);

        messageLabel.setText("Message");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                        .addContainerGap()
                                                        .addGroup(layout.createParallelGroup(
                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                        .addComponent(messageLabel)
                                                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                        .addComponent(userTextInput,
                            javax.swing.GroupLayout.PREFERRED_SIZE, 356,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                        .addComponent(sendButton,
                            javax.swing.GroupLayout.PREFERRED_SIZE, 91,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                        .addGap(0,
                            0, Short.MAX_VALUE)).addComponent(jScrollPane1))
                                                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING)
                                      .addGroup(layout.createSequentialGroup()
                                                      .addContainerGap()
                                                      .addComponent(jScrollPane1,
                    javax.swing.GroupLayout.PREFERRED_SIZE, 316,
                    javax.swing.GroupLayout.PREFERRED_SIZE)
                                                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                      .addGroup(layout.createParallelGroup(
                        javax.swing.GroupLayout.Alignment.BASELINE)
                                                                      .addComponent(userTextInput,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 28,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                      .addComponent(sendButton,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 28,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                      .addComponent(messageLabel,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                      .addContainerGap()));

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

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String usersInput;
        usersInput = userTextInput.getText();
        os.println(usersInput);
        userTextInput.setText("");
        serverInput.append("Sending Message...");
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        /*
        * Set the Nimbus look and feel
        */

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
        * If Nimbus (introduced in Java SE 6) is not available, stay with the
        * default look and feel. For details see
        * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */

        /*
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel("javax.swing.plaf.basic.BasicLookAndFeel");

                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Client_UI.class.getName())
                                        .log(java.util.logging.Level.SEVERE, null,
                    ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Client_UI.class.getName())
                                        .log(java.util.logging.Level.SEVERE, null,
                    ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Client_UI.class.getName())
                                        .log(java.util.logging.Level.SEVERE, null,
                    ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Client_UI.class.getName())
                                        .log(java.util.logging.Level.SEVERE, null,
                    ex);
            }
        */

        //</editor-fold>
        /*
        * Create and display the form
        */
        java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    //new Client_UI().setVisible(true);
                } //END RUN
            });

        try {
            host = InetAddress.getLocalHost();
        } catch (UnknownHostException uhEx) {
            System.out.println("\nHost ID not found!\n");
            System.exit(1);
        }

        chat();
    } //END MAIN

    private static void chat() {
        Socket socket = null;

        try {
            clientSocket = new Socket(host, PORT);
            //inputLine = new BufferedReader(new InputStreamReader(System.in));
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.out.println("Couldn't Connect To The Host!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Couldn't get the I/O going!");
        }

        if ((clientSocket != null) && (os != null) && (is != null)) {
            Client_UI ui = new Client_UI();
	    ui.setVisible(true);
            new Thread(ui).start();
        } //END IF
    } //End chat();

    public void run() {
        String responseLine;

        // Keep reading from the socket until we receive the "logout" from the server,
        // once we get that then we break.
        try {
	    System.out.println(Thread.currentThread());
            while ((responseLine = is.readLine()) != null) {
                System.out.println(responseLine);

                //serverInput.append(responseLine + "\n");
                java.awt.EventQueue.invokeLater(new GuiUpdater(responseLine));

                if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                } //END IF
            }

            //closed = true;
            is.close();
            os.close();
            clientSocket.close();
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    } //END run()

    private class GuiUpdater implements Runnable {
        private String displayString;

        public GuiUpdater(String displayString) {
            this.displayString = displayString;
        }

        public void run() {
            serverInput.append(String.format("\n%s", displayString));
        }
    }

    // End of variables declaration
}


Was This Post Helpful? 1
  • +
  • -

#11 Sasquatch3o3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 03-April 11

Re: I am having a problem with my GUI not appending the String

Posted 29 February 2012 - 02:41 PM

g00se!!!!! You Figured it out!!! Holy CRAP! I would have never thought I created my GUI twice! It makes sense now! I will have to smooth it out too! But I can finally quit sweating bullets. I give you mad props. Fuzzyness I will give you some credit too, thanks a million fellas.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1