views:

40

answers:

1

I am doin a Some Socket Programing Stuff in Java.. Here i have created a button(Create Server)..and when i click it ,it starts server...but i want to change the button name to (Stop Server) after Starting the server... so i did this.. but when i press start server it starts and the button name remains the same...

and when a client gets connected to it ,then it change the name to stop server...

tell me whats the wrong with this code??

Here is My a SomePart Of Code...

public void actionPerformed(ActionEvent ex)
{
    if(ex.getActionCommand() == "CreateServer")
    {
        bt1.setText("Stop Server");
        bt2.setEnabled(false);
        b5.setText("Server Started On Port " + tf2.getText());      
        System.out.println("Server started 1");
            create(Integer.parseInt(tf2.getText()));  //my func. to create server
        System.out.println("Server started 2");
    }       
}

and my create() fucn. contains some sockets and thread...so tell me what the problem...

+2  A: 

You are running your server probably in your AWT Thread. So, this means this thread cannot repaint your frame and the button caption doesn't change.

So make a new Thread for your server (this code in your button action listener):

Runnable serverRunnable = new Runnable()
{
    public void run()
    {
        create(Integer.parseInt(tf2.getText()));  //my func. to create server
    }
};
Thread serverThread = new Thread(serverRunnable);
serverThread.start();

After executing this code, the AWT Thread launched a new Thread and doesn't have to run the server by himself and can resume repainting the frame or components wen needed.

Martijn Courteaux
thanx ...it works...just tell me how did u make the thread in a func. it self...every time i make thread ,i used to make a new class implemented by runnable...and what does this exactly does "Runnable serverRunnable = new Runnable()"
Vizay Soni
@vs4vijay: That is just the same. Implementing it in a new class or doing it like this. It is exactly the same if you add an action listener: you are not creating a new file, just like this.
Martijn Courteaux