Click here to Skip to main content
15,919,749 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hai,I am trying to create a chat program in core java using nio channels in which the server responds multiple clients at a time.I created 3 clases namely client_login,client_form and nioserver.But the problem is that if the the user login sucessfully the frame for chating apperes,but the send and exit button that i am created is not appeares in the frame as well as it is not possible to close the frame.here is my client_form file.

Java
/**
 *
 * @author appuraj.kr
 */
public class Client_form extends javax.swing.JFrame {

    
    /**
     * Creates new form
     */
    public Client_form(String uname,String hostname) throws IOException 

/*initialise here*/
    {
         super(uname);
       this.uname=uname;
       this.hostname=hostname;
       //setTitle(uname);
        System.out.println(uname+""+hostname);
               
       socketAddress = new InetSocketAddress(hostname,7789);
        charset = Charset.forName("ISO-8859-1");
        decoder = charset.newDecoder();
        encoder = charset.newEncoder();
        buffer = ByteBuffer.allocateDirect(1024);
        buffer1 = ByteBuffer.allocateDirect(1024);
        charBuffer = CharBuffer.allocate(1024);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);
 // Open Selector
        selector = Selector.open();
            // Register interest in when connection90 
       channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE|SelectionKey.OP_READ);
        
        setVisible(true);
        
        initComponents();
       // client_start();
       setVisible(true);
    }

    /**
     * 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.
     */
      public void client_start(){
        
        String line=null;
        
        try {
               
  while (selector.select(500) > 0)
            {
                // Get set of ready objects
                Set readyKeys = selector.selectedKeys();
                Iterator readyItor = readyKeys.iterator();

                 // Walk through set
                while (readyItor.hasNext())
                { 
                       
                    // Get key from set
                    SelectionKey key = (SelectionKey)readyItor.next();

                    // Remove current entry
                    readyItor.remove();

                    // Get channel
                    SocketChannel keyChannel = (SocketChannel)key.channel();

                    if (key.isConnectable())
                    {
                        //System.out.println(uname);
                        // Finish connection
                        System.out.println("server foundllllllllllllll");
                        System.out.println("connected");
                        //System.out.println("user name is"+uname);
                        if (keyChannel.isConnectionPending())
                        {
                            keyChannel.finishConnect();
                        }
                        
                        
                        
                        

                        buffer1.clear();
                        System.out.println("username"+uname);
                                 buffer1=ByteBuffer.wrap(new String(uname).getBytes());
                                 keyChannel.write(buffer1);
                       
                        buffer1.clear();
                       
                        
                        try
                        {
                           
                            Thread.sleep(1000);
                            buffer1.clear();
                            charBuffer.clear();
                            keyChannel.read(buffer1);
                            buffer1.flip();
                            decoder.decode(buffer1, charBuffer, false);
                            charBuffer.flip();
                            String data=charBuffer.toString();
                            System.out.println("inside readmmmmmmmmmmm"+data);
                            System.out.println("before passing appendtext"+data);
                          
                             tamsg.append("hai "+data+ "\n");
                            buffer1.clear();
                            charBuffer.clear();
                                                     
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                        
                      
                            
                   }
                 
      }
            
            }        /* while(true) 
                {
                    line = br.readLine();
                    taMessages.append(line + "\n");
                } // end of while */
            } catch(Exception ex) {}
        
    }
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tamsg = new java.awt.TextArea();
        tinput = new javax.swing.JTextField();
        btnsnd = new javax.swing.JButton();
        btnexit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tamsg.setEditable(false);

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

        btnexit.setText("Exit");
        btnexit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnexitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tamsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tinput, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnsnd)
                .addGap(26, 26, 26)
                .addComponent(btnexit)
                .addGap(0, 98, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tamsg, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tinput, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(btnsnd)
                    .addComponent(btnexit))
                .addContainerGap())
        );

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

    private void btnsndActionPerformed(java.awt.event.ActionEvent evt) {                                       
String line=null;
String data=null;
        line=tinput.getText();
           buffer1.clear();
           buffer1=ByteBuffer.wrap(new String(tinput.getText()).getBytes());
           try
           {
               
                             
                 channel.write(buffer1);
                 tamsg.append(uname+": "+line+ "\n");
                 buffer1.clear();
                 channel.read(buffer1);
                 buffer1.flip();
                 buffer1.rewind();
                 //buffer1.flip();
                 buffer1.clear();
                 decoder.decode(buffer1, charBuffer, false);
                 charBuffer.flip();
                 data=charBuffer.toString();
                 System.out.println("server"+data);
                 tamsg.append("server:"+data+ "\n");
                 charBuffer.clear();
                 buffer1.clear();
           
           } 
           
           catch (IOException ex) 
            {
                Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            tinput.setText("");
            buffer1.clear();//add your handling code here:
    }                                      

    private void btnexitActionPerformed(java.awt.event.ActionEvent evt) {                                        
System.exit(0);        // TODO add your handling code here:
    }                                       

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnexit;
    private javax.swing.JButton btnsnd;
    private java.awt.TextArea tamsg;
    private javax.swing.JTextField tinput;
    // End of variables declaration                   
}
Posted
Updated 11-Apr-12 22:52pm
v2
Comments
Nagy Vilmos 12-Apr-12 4:53am    
Always put your code in <pre> tags, readability matters.

EDITED:

..because your function initComponents() is working with copies of the original components.

You should make the components to be members and then work on the original member.


Also please clean the spaghetti codes in that function initComponents() up, that is a horrible mess.

It's even worse. I would suggest to delete the GUI and start over again. This time write it properly. That code in the function initComponents() is pure chaos - as if someone threw code into a bin.

I can also recommend to separate GUI from functional code. Why not making 2 classes (plus a starter class which contains the main)?
 
Share this answer
 
v3
I have taken your code and added the missing imports and member variables.

When I run it, the two buttons are shown no problem and the exit button closes the form.

Further to Torsten's comments, I would recommend removing all the non-UI activity from the form. You need a new Class, I'll call it ClientSession and move all the comms and messaging into that.

As a simple rule of thumb, if it does not read from the form or write to it, then it should not be in the form.
 
Share this answer
 
Comments
TorstenH. 12-Apr-12 7:06am    
it works?
I just copied the code to my playground and saw way to much red. Didn't even think of solving the imports members and stuff.
Nagy Vilmos 12-Apr-12 9:08am    
A couple of imports and half a dozen missing decelerations fixed it.
Arjun Menon U.K 16-Apr-12 3:01am    
i also tried in that way also.but the it shows the same problem again..
Nagy Vilmos 16-Apr-12 4:46am    
What do you mean by "same problem"?

Have you tried debugging? Fire up any half decent IDE, step through the code and see what it throws out.
Arjun Menon U.K 16-Apr-12 5:31am    
This is my client_login code
public class chatlogin1 extends JFrame implements ActionListener{
JButton login,Register;
JLabel label1,label2,label3;
JTextField text1,text2,text3;
public chatlogin1()
{
try {
setTitle("Loginform");
setLayout(null);
label1=new JLabel();
label2=new JLabel();
label3=new JLabel();
label1.setText("ServerIP:");
label2.setText("Username:");
label3.setText("Password");
text1=new JTextField(20);
text2=new JTextField(20);
text3=new JPasswordField(20);
label1.setBounds(100,70,100,20);
text1.setBounds(200,70,200,20);
label2.setBounds(100,100,100,20);
text2.setBounds(200,100,200,20);
label3.setBounds(100,130,100,20);
text3.setBounds(200,130,200,20);
login=new JButton("login");
Register=new JButton("Register");
login.addActionListener(this);
Register.addActionListener(this);
login.setBounds(130,169,100,20);
Register.setBounds(240, 169, 100,20);

add(label1);
add(label2);
add(label3);
add(text1);
add(text2);
add(text3);
add(login);
add(Register);

setSize(500, 500);
setVisible(true);

//pack();
ChatClient cc=new ChatClient("appu","localhost");
} catch (IOException ex) {
Logger.getLogger(chatlogin1.class.getName()).log(Level.SEVERE, null, ex);
}

}

public void actionPerformed(ActionEvent ae){
try {
ChatClient cc=new ChatClient("appu","localhost");
} catch (IOException ex) {
Logger.getLogger(chatlogin1.class.getName()).log(Level.SEVERE, null, ex);
}


}


public static void main(String[] args) throws IOException {
chatlogin1 cl=new chatlogin1();

}
}
when i click login button ,i want to go to the chat window titled with username. following is the code for chating window

public class ChatClient extends JFrame implements ActionListener
{
public String uname;
public JTextArea taMessages;
public JTextField tfInput;
public JButton btnSend,btnExit;
public BufferedReader br;
public SocketChannel channel = null;
public Selector selector;
public InetSocketAddress socketAddress;
public Charset charset ;
public CharsetDecoder decoder;
public CharsetEncoder encoder;
public ByteBuffer buffer ;
public ByteBuffer buffer1;
public CharBuffer charBuffer ;
int k=0;
int f=0;
int flag=0;
ResultSet rs=null;
ResultSet rs1=null;
String sql=null;
String user_name=null;
DBConnection dbc=new DBConnection();

public ChatClient(String uname,String servname) throws IOException
{

super(uname); // set title for frame
this.uname = uname;



//System.out.println(this.uname);




// br=new BufferedReader(new InputStreamReader(System.in));
socketAddress = new InetSocketAddress(servname,7789);
charset = Charset.forName("ISO-8859-1");
decoder = charset.newDecoder();
encoder = charset.newEncoder();
buffer = ByteBuffer.allocateDirect(1024);
buffer1 = ByteBuffer.allocateDirect(1024);
charBuffer = CharBuffer.allocate(1024);
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(socketAddress);
// Open Selector
selector = Selector.open();
// Register interest in when connection90
channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE|SelectionKey.OP_READ);



This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900