Home arrow static arrow Java Programming [Archive] - HELPME!
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - HELPME!
10 Duke Stars available
This topic has 12 replies on 1 page.

Posts:15
Registered: 8/16/03
HELPME!  
Jul 9, 2004 3:38 PM



 
i wrote my one own chatroom program and i use a jTextArea to display the messages. But at the end of each line these "" show up. i spent hours trying to get rid of them but nothing seemed to work. If anybody has any ideas or knows what the problem is please help me...thanks
 

Posts:3,258
Registered: 00-08-28
Re: HELPME!  
Jul 9, 2004 4:09 PM (reply 1 of 12)



 
I donot have access to the code you arote so I cannot say anything for sure but these boxes normally appear if you are using special characters I mean other than iso-8859-1 and you donot have the fonts installed on your machine.
 

Posts:3,534
Registered: 9/30/99
Re: HELPME!  
Jul 9, 2004 4:45 PM (reply 2 of 12)



 
Are they at the end of each and every line every time? Or just sometimes? They are just nonprinting characters as stated earlier.

Are you doing a hardcode of chr(10) + chr(13) for return and linefeed?
 

Posts:474
Registered: 3/12/04
Re: HELPME!  
Jul 9, 2004 10:34 PM (reply 3 of 12)



 
See this is some unrecognizable ASCII code.Either u r printing some char ,though 13 would not give u this block.Kindly let me know which version of java are u using
 

Posts:49
Registered: 2/5/04
Re: HELPME!  
Jul 10, 2004 3:06 AM (reply 4 of 12)



 
Those blocks might be new line characters or tab characters which you are trying to put into the textarea.
Just print some code here so that we can know the source of the problem

Karthik
 

Posts:15
Registered: 8/16/03
Re: HELPME!  
Jul 10, 2004 2:48 PM (reply 5 of 12)



 
CLIENTFRAME CLASS:
package chatprogram;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

/**
*

Title: Chat Program

*

Description: Simple Program For Chating

*

Copyright: Copyright (c) 2004

*

Company: Student

* @author Nick DeLuca
* @version 1.0
*/

public class ClientFrame extends JFrame implements Runnable, WindowListener {
private GridLayout gridLayout1 = new GridLayout();
private JButton sendButton = new JButton();
private JTextField jTextField1 = new JTextField();
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextArea jTextArea1 = new JTextArea();
private JMenuBar jMenuBar1 = new JMenuBar();
private JMenu jFileMenu = new JMenu();
private JMenuItem jConnectItem = new JMenuItem();
private JMenuItem jDisconnectItem = new JMenuItem();
private JMenuItem jExitItem = new JMenuItem();
private ChatClient cc = new ChatClient();
private boolean connected = false;
private String ip;
private String msg;
private JMenuItem jClearItem = new JMenuItem();
private JMenu jHelpMenu = new JMenu();
private JMenuItem jAboutItem = new JMenuItem();
private Thread runner = new Thread(this);
private boolean isText;
public ClientFrame() {
try {
Init();

}
catch (Exception ex) {
ex.printStackTrace();
}
}

void Init() throws Exception {
this.addWindowListener(this);
sendButton.setBounds(new Rectangle(228, 12, 104, 23));
sendButton.setToolTipText("Send Message");
sendButton.setActionCommand("Send");
sendButton.setMnemonic('S');
sendButton.setSelected(false);
sendButton.setText("Send");
this.getContentPane().setLayout(null);
jTextField1.setToolTipText("Type Your Message Here");
jTextField1.setText("");
jTextField1.setBounds(new Rectangle(15, 12, 212, 23));
this.setSize(new Dimension(353, 344));
this.setJMenuBar(jMenuBar1);
this.setResizable(false);
this.setState(Frame.NORMAL);
this.setTitle("ChatClient");
jScrollPane1.setBounds(new Rectangle(15, 40, 317, 243));
jTextArea1.setToolTipText("Incoming Messages Are Printed Here");
jTextArea1.setEditable(false);
jTextArea1.setText("");
jTextArea1.setTabSize(8);
jTextArea1.setWrapStyleWord(true);
jMenuBar1.setRequestFocusEnabled(true);
jFileMenu.setMnemonic('F');
jFileMenu.setText("File");
jConnectItem.setMnemonic('C');
jConnectItem.setText("Connect");
jConnectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke('N', java.awt.event.KeyEvent.CTRL_MASK, false));
jDisconnectItem.setMnemonic('D');
jDisconnectItem.setText("Disconnect");
jDisconnectItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke('D', java.awt.event.KeyEvent.CTRL_MASK, false));
jExitItem.setMnemonic('E');
jExitItem.setText("Exit");
jExitItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke('E', java.awt.event.KeyEvent.CTRL_MASK, false));
jClearItem.setSelected(false);
jClearItem.setText("Clear Messages");
jClearItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke('M', java.awt.event.KeyEvent.CTRL_MASK, false));
jHelpMenu.setMnemonic('H');
jHelpMenu.setRolloverEnabled(false);
jHelpMenu.setText("Help");
jAboutItem.setMnemonic('A');
jAboutItem.setText("About");
jAboutItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke('U', java.awt.event.KeyEvent.CTRL_MASK, false));
this.getContentPane().add(jTextField1, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(sendButton, null);
jScrollPane1.getViewport().add(jTextArea1, null);
jMenuBar1.add(jFileMenu);
jMenuBar1.add(jHelpMenu);
jFileMenu.add(jConnectItem);
jFileMenu.add(jDisconnectItem);
jFileMenu.add(jClearItem);
jFileMenu.addSeparator();
jFileMenu.add(jExitItem);
jHelpMenu.add(jAboutItem);
jTextField1.setEnabled(false);
sendButton.setEnabled(false);
jTextArea1.setEnabled(false);
jDisconnectItem.setEnabled(false);
jClearItem.setEnabled(false);
isText = false;
this.getRootPane().setDefaultButton(sendButton);

jClearItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
jTextArea1.setText("");
isText = false;
}

});

jAboutItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(ClientFrame.this, "A Simple Chat Program\n" + "Made By: Nick Deluca", "About", JOptionPane.INFORMATION_MESSAGE);
}

});

jConnectItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
ip = JOptionPane.showInputDialog(ClientFrame.this,"Please type the IP address you wish to connect to.").trim();
if(ip != null) {
if (cc.connect(ip)) {
connected = true;
jTextField1.setEnabled(true);
sendButton.setEnabled(true);
jTextArea1.setEnabled(true);
jDisconnectItem.setEnabled(true);
jConnectItem.setEnabled(false);
}
else {
JOptionPane.showMessageDialog(ClientFrame.this, "Error While Trying To Connect", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}

});
jExitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(connected){
cc.sendMessage("quit");
}
System.exit(0);
}

});

jDisconnectItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(connected){
cc.sendMessage("quit");
connected = false;
jTextField1.setEnabled(false);
sendButton.setEnabled(false);
jTextArea1.setEnabled(false);
jDisconnectItem.setEnabled(false);
jConnectItem.setEnabled(true);
jTextArea1.setText("");
isText = false;
}
}

});

sendButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String msg = jTextField1.getText().trim();
jTextField1.setText("");
if(connected) {
cc.sendMessage(msg);

}
}
});

}

public static void main(String[] args) {
ClientFrame clientFrame = new ClientFrame();
clientFrame.show();
clientFrame.start();

}
public void start(){

runner.start();
}
public void run() {

cc.init();
while(true) {

if(isText) {
jClearItem.setEnabled(true);
}
else {
jClearItem.setEnabled(false);
}
if(connected) {
msg = cc.readIncomingMessages();
if (msg != null) {
jTextArea1.append(msg);
isText = true;
}
}
}
}

public void windowClosing(WindowEvent e) {
if(connected){
cc.sendMessage("quit");
}
System.exit(0);
}
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}

 

Posts:15
Registered: 8/16/03
Re: HELPME!  
Jul 10, 2004 2:49 PM (reply 6 of 12)



 
CHATCLIENT CLASS:
package chatprogram;

import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
import java.util.*;
import java.net.*;
import java.io.*;
/**
*

Title: Chat Program

*

Description: Simple Program For Chating

*

Copyright: Copyright (c) 2004

*

Company: Student

* @author Nick DeLuca
* @version 1.0
*/

public class ChatClient {
private static final int BUFFER_SIZE = 255;
private static final long CHANNEL_WRITE_SLEEP = 10L;
private static final int PORT = 10997;

private static ByteBuffer writeBuffer;
private ByteBuffer readBuffer;
private boolean running;
private static SocketChannel channel;
private String host;
private Selector readSelector;
private CharsetDecoder asciiDecoder;

public void init() {
this.connect(host);
}
public ChatClient() {

writeBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
readBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
asciiDecoder = Charset.forName( "US-ASCII").newDecoder();;
}


public boolean connect(String hostname) {
this.host = hostname;
try {
readSelector = Selector.open();
String addr = hostname;
channel = SocketChannel.open(new InetSocketAddress(addr, PORT));
channel.configureBlocking(false);
channel.register(readSelector, SelectionKey.OP_READ, new StringBuffer());

}
catch (UnknownHostException uhe) {
return false;
}
catch (ConnectException ce) {
return false;
}
catch (Exception e) {
return false;
}
return true;
}

public String readIncomingMessages() {
// check for incoming mesgs
try {
// non-blocking select, returns immediately regardless of how many keys are ready
readSelector.selectNow();

// fetch the keys
Set readyKeys = readSelector.selectedKeys();

// run through the keys and process
Iterator i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
SocketChannel channel = (SocketChannel) key.channel();
readBuffer.clear();

// read from the channel into our buffer
long nbytes = channel.read(readBuffer);

// check for end-of-stream
if (nbytes == -1) {
System.out.println("disconnected from server: end-of-stream");
channel.close();

}
else {
// grab the StringBuffer we stored as the attachment
StringBuffer sb = (StringBuffer)key.attachment();

// use a CharsetDecoder to turn those bytes into a string
// and append to our StringBuffer
readBuffer.flip( );
String str = asciiDecoder.decode(readBuffer).toString();
sb.append(str);
readBuffer.clear();

// check for a full line and write to STDOUT
String line = sb.toString();
if ((line.indexOf("\n") != -1) || (line.indexOf("\r") != -1)) {
sb.delete(0,sb.length());
msg = line;
return msg;
}
}
}
}
catch (IOException ioe) {
}
catch (Exception e) {
}
return null;
}

public static void sendMessage(String mesg) {
prepWriteBuffer(mesg);
channelWrite(channel, writeBuffer);
}

private static void prepWriteBuffer(String mesg) {
// fills the buffer from the given string
// and prepares it for a channel write
writeBuffer.clear();
writeBuffer.put(mesg.getBytes());
writeBuffer.putChar('\n');
writeBuffer.flip();
}

private static void channelWrite(SocketChannel channel, ByteBuffer writeBuffer) {
long nbytes = 0;
long toWrite = writeBuffer.remaining();

// loop on the channel.write() call since it will not necessarily
// write all bytes in one shot
try {
while (nbytes != toWrite) {
nbytes += channel.write(writeBuffer);

try {
Thread.sleep(CHANNEL_WRITE_SLEEP);
}
catch (InterruptedException e) {}
}
}
catch (ClosedChannelException cce) {
}
catch (Exception e) {
}

// get ready for another write if needed
writeBuffer.rewind();
}

private String msg;
}

 

Posts:15
Registered: 8/16/03
Re: HELPME!  
Jul 10, 2004 2:50 PM (reply 7 of 12)



 
CHATSERVER CLASS:
package chatprogram;

import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.net.*;
import java.io.*;

/**
*

Title: Chat Program

*

Description: Simple Program For Chating

*

Copyright: Copyright (c) 2004

*

Company: Student

* @author Nick DeLuca
* @version 1.0
*/

public class ChatServer extends Thread {
private static final int BUFFER_SIZE = 255;
private static final long CHANNEL_WRITE_SLEEP = 10L;
private static final int PORT = 10997;

private ServerSocketChannel sSockChan;
private Selector acceptSelector;
private Selector readSelector;
private SelectionKey selectKey;
private boolean running;
private LinkedList clients;
private ByteBuffer readBuffer;
private ByteBuffer writeBuffer;
private CharsetDecoder asciiDecoder;

public static void main(String args[]) {

// instantiate the ChatterServer and fire it up
ChatServer cs = new ChatServer();
cs.start();
}

public ChatServer() {
clients = new LinkedList();
readBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
writeBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
asciiDecoder = Charset.forName( "US-ASCII").newDecoder();;
}

private void initServerSocket() {
try {
// open a non-blocking server socket channel
sSockChan = ServerSocketChannel.open();
sSockChan.configureBlocking(false);

// bind to localhost on designated port
InetAddress addr = InetAddress.getLocalHost();
sSockChan.socket().bind(new InetSocketAddress(addr, PORT));

// get a selector for multiplexing the client channels
readSelector = Selector.open();
}
catch (Exception e) {
System.out.println("error initializing server");
}
}

public void run() {
initServerSocket();

System.out.println("ChatterServer running");
running = true;
int numReady = 0;

// block while we wait for a client to connect
while (running) {
// check for new client connections
acceptNewConnections();

// check for incoming mesgs
readIncomingMessages();

// sleep a bit
try {
Thread.sleep(100);
}
catch (InterruptedException ie) {
}
}
}

private void acceptNewConnections() {
try {
SocketChannel clientChannel;
// since sSockChan is non-blocking, this will return immediately
// regardless of whether there is a connection available
while ((clientChannel = sSockChan.accept()) != null) {
addNewClient(clientChannel);
System.out.println("got connection from: " + clientChannel.socket().getInetAddress());
sendBroadcastMessage("login from: " + clientChannel.socket().getInetAddress(), clientChannel);
sendMessage(clientChannel, "Welcome the chat room, there are " +
clients.size() + " users online.");
sendMessage(clientChannel, "Type 'quit' to exit.");
}
}
catch (IOException ioe) {
System.out.println("error during accept(): ");
}
catch (Exception e) {
System.out.println("exception in acceptNewConnections()" + e);
}
}

private void readIncomingMessages() {
try {
// non-blocking select, returns immediately regardless of how many keys are ready
readSelector.selectNow();

// fetch the keys
Set readyKeys = readSelector.selectedKeys();

// run through the keys and process
Iterator i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
SocketChannel channel = (SocketChannel) key.channel();
readBuffer.clear();

// read from the channel into our buffer
long nbytes = channel.read(readBuffer);

// check for end-of-stream
if (nbytes == -1) {
System.out.println("disconnect: " + channel.socket().getInetAddress() + ", end-of-stream");
channel.close();
clients.remove(channel);
sendBroadcastMessage("logout: " + channel.socket().getInetAddress() , channel);
}
else {
// grab the StringBuffer we stored as the attachment
StringBuffer sb = (StringBuffer)key.attachment();

// use a CharsetDecoder to turn those bytes into a string
// and append to our StringBuffer
readBuffer.flip( );
String str = asciiDecoder.decode( readBuffer).toString( );
readBuffer.clear( );
sb.append( str);

// check for a full line
String line = sb.toString();
if ((line.indexOf("\n") != -1) || (line.indexOf("\r") != -1)) {
line = line.trim();
if (line.startsWith("quit")) {
// client is quitting, close their channel, remove them from the list and notify all other clients
System.out.println("got quit msg, closing channel for : " + channel.socket().getInetAddress());
channel.close();
clients.remove(channel);
sendBroadcastMessage("logout: " + channel.socket().getInetAddress(), channel);
}
else {
// got one, send it to all clients
System.out.println("broadcasting: " + line);
sendBroadcastMessage(channel.socket().getInetAddress() + ": " + line, channel);
sb.delete(0,sb.length());
}
}
}

}
}
catch (IOException ioe) {
System.out.println("error during select(): " + ioe);
}
catch (Exception e) {
System.out.println("exception in run()");
}

}

private void addNewClient(SocketChannel chan) {
// add to our list
clients.add(chan);

// register the channel with the selector
// store a new StringBuffer as the Key's attachment for holding partially read messages
try {
chan.configureBlocking( false);
SelectionKey readKey = chan.register(readSelector, SelectionKey.OP_READ, new StringBuffer());
}
catch (ClosedChannelException cce) {
}
catch (IOException ioe) {
}
}

private void sendMessage(SocketChannel channel, String mesg) {
prepWriteBuffer(mesg);
channelWrite(channel, writeBuffer);
}

private void sendBroadcastMessage(String mesg, SocketChannel from) {
prepWriteBuffer(mesg);
Iterator i = clients.iterator();
while (i.hasNext()) {
SocketChannel channel = (SocketChannel)i.next();
channelWrite(channel, writeBuffer);
}
}

private void prepWriteBuffer(String mesg) {
// fills the buffer from the given string
// and prepares it for a channel write
writeBuffer.clear();
writeBuffer.put(mesg.getBytes());
writeBuffer.putChar('\n');
writeBuffer.flip();
}

private void channelWrite(SocketChannel channel, ByteBuffer writeBuffer) {
long nbytes = 0;
long toWrite = writeBuffer.remaining();

// loop on the channel.write() call since it will not necessarily
// write all bytes in one shot
try {
while (nbytes != toWrite) {
nbytes += channel.write(writeBuffer);

try {
Thread.sleep(CHANNEL_WRITE_SLEEP);
}
catch (InterruptedException e) {}
}
}
catch (ClosedChannelException cce) {
}
catch (Exception e) {
}

// get ready for another write if needed
writeBuffer.rewind();
}
}

 

Posts:9,091
Registered: 8/15/01
Re: HELPME!  
Jul 10, 2004 3:41 PM (reply 8 of 12)



 
When you post code, please use[code] and [/code] tags as described in [url=http://forum.java.sun.com/features.jsp#Formatting]Formatting Help[/url] on the message entry page. It makes it much easier to read.
 

Posts:73
Registered: 7/3/04
Re: HELPME!  
Jul 10, 2004 10:22 PM (reply 9 of 12)



 
Actually you should submit the code for give a proper answer.
Probably this happen due to some special character that u r trying to add.
(If u r trying to add some unicode stuff this will arise if you don't have that language package.)
 

Posts:73
Registered: 7/3/04
Re: HELPME!  
Jul 10, 2004 10:25 PM (reply 10 of 12)



 
Sorry the god **** code is there at the bottom.
will check it and give u a reply
 

Posts:49
Registered: 6/17/04
Re: HELPME!  
Jul 11, 2004 12:26 AM (reply 11 of 12)



 
May be u are outputting some formatted text that is why it is having trouble!
 

Posts:55
Registered: 6/12/04
Re: HELPME!  
Jul 11, 2004 3:53 AM (reply 12 of 12)



 
if u are using \n for new line, it might be like it is creating the problem use instead

System.getProperty("line.separator")
 
This topic has 12 replies on 1 page.