Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7596633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:57:54+00:00 2026-05-30T21:57:54+00:00

After solve my problem to handle add label into my jlabel backgroudn in previous

  • 0

After solve my problem to handle add label into my jlabel backgroudn in previous question. I got new trouble when develop a client server in hang man for 2 players to play game.

Firstly when user choose mode 2 players. Client will send a message to Server is “twoPMode”

From TCP server , server receive this message and put it into a method handle input from client.

in this method, i have a global variable called playerId and it has 2 method getter/stter

detail:

When user send message “twoPMode” to server, server will call this method and in this method it receive input from client and handle, if input from client is twoPMode it will set Playerid = “001” and if other client send message twoPMode to server it will set playerid = “002” , because i just want 2 client can connect to server to play game, if client 3 connect and send twoPMode to server i will destroy connection of client 3.

My trouble is when client 1 and client 2 send message twoPMode to server it also receive id is 001, it fail because i want who is connect to server first will get playerid is 001 and second is get player id is 002, but my code just respond to client is 001 although 2 clients connect to server

and my code – i delete some generate code from netbean to initial component

Server side:

class handle input from client

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

import java.util.Random;

/**
 *
 * @author J2ME NewBiew
 */
public class gameHandle {

    private static final int WAITING = 0;
    private static final int onePMode = 1;
    private static final int getWord = 2;
    private static final int PlayonePmode = 3;
    private static final int NUMJOKES = 5;
    private String keyword = "";
    private static final int mode = 4;
    private int state = WAITING;
    private int countError = 0;
    private String playerid = "000";

    public String getPlayerid() {
        return playerid;
    }


    //array word list
        String[] words = {"laptop", "network", "device", "game", "mobile",
    "word", "november", "december", "signal", "internet","localhost","boot", "socket",
    "client", "server", "port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
    "computer", "microsoft", "lan"};

    //this method get random word from array    
    public String getWord(){
        Random r = new Random();
        String randomString = words[r.nextInt(words.length)];
        return randomString;
    }



    public String processInput(String theInput) {
        String theOutput = null;

        if (state == WAITING) {
            theOutput = "Hello Hangman Client";
            state = mode;
        } else if(state == mode){

            if(theInput.equalsIgnoreCase("onePMode")){
                theOutput = "onePMode" ;
                state = onePMode;
            }else if(theInput.equalsIgnoreCase("")){
                state = WAITING;
            }else if(theInput.equalsIgnoreCase("twoPMode")){
               if(playerid.equals("000")){
                   setPlayerid("001");
                   theOutput = "001";
                   playerid = "001";
                   System.out.println("Thu cai coi 01");
               }
               else if(playerid.equals("001")){
                   setPlayerid("002");
                   theOutput = "002";
                   playerid = "002";
                   System.out.println("Thu cai coi 02");
               }

            }

        } else if (state == onePMode) {
            if (theInput.equalsIgnoreCase("getWord")) {
                keyword = getWord();
                theOutput = keyword;
                state = PlayonePmode;

            } 
        }else if (state == PlayonePmode) {
            if(theInput.equalsIgnoreCase("getWord")){
                theOutput = " chuyen sang getword";
                state = getWord;

            }else if (keyword.contains(theInput)) {
                theOutput = "containt";
            } else {
                if(countError <9){
                    theOutput = "Khong contain";
                     countError++;
                }else if(countError>=9){
                   theOutput = "Game Over!";
                }
            }
        }   if (state == getWord){
            keyword = getWord();
            theOutput = keyword;
            state = PlayonePmode;
        }
         System.out.println("Player ID: " +  playerid);
        return theOutput;
    }

    public void setPlayerid(String playerid) {
        this.playerid = playerid;
    }
}

Class server open thread, send data to client and receive data from client:

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author J2ME NewBiew
 */
public class TCPServerThread extends Thread{

    Socket client = null;
    BufferedReader in;
    String statusBuffer = new String();
    String intputLine, outputLine;
    public TCPServerThread(Socket socket){
        client = socket;
    }

    public void run(){

    try {
        PrintWriter out = new PrintWriter(client.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    client.getInputStream()));

        String inputLine, outputLine;
        gameHandle g = new gameHandle();
        outputLine = g.processInput(null);
        out.println(outputLine);

        while ((inputLine = in.readLine()) != null) {
        outputLine = g.processInput(inputLine);
                System.out.println(outputLine);
                if(inputLine.equals("getWord")){
                    System.out.println(inputLine);
                }

        out.println(outputLine);
        if (inputLine.equals("Bye"))
            break;
        }
        out.close();
        in.close();
        client.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    }

}

Client side: i use 2 panel , one 1 home page of game and 1 is two players mode

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

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
import srpclient.ConnectionTCP;
import srpclient.about.aboutPanel;
import srpclient.player1.onePlayer;
import srpclient.twoplayers.twoPlayers;

/**
 *
 * @author J2ME NewBiew
 */
public final class Home extends javax.swing.JPanel {

    aboutPanel aboutPanel;
    onePlayer onePlayerMode;
    String serverAddress;
    twoPlayers twoPlayerMode;
     ConnectionTCP c;
    /**
     * Creates new form Home
     */
    public Home(String ipAddress) {
        initComponents();

         //conn = new ConnectionTCP(ipAddress);
         this.serverAddress = ipAddress;

         initialPanel();
       //  conn.closeConnection();

    }

    public void initialPanel(){
        aboutPanel = new aboutPanel();


    }

    public void changeImage(JButton bt, String imgPath){
        bt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/"+imgPath+".jpg")));
    }

    public void setTooltipforButton(JButton bt, String Tooltip){
        bt.setToolTipText(Tooltip);
    }



    private void player1Hover(java.awt.event.MouseEvent evt) {                              
        // TODO add your handling code here:
        changeImage(btPlayer1, "player1Hover");
        setTooltipforButton(btPlayer1, "Play game with 1 player mode");
    }                             

    private void player1MouseExit(java.awt.event.MouseEvent evt) {                                  
        // TODO add your handling code here:
        changeImage(btPlayer1, "player1");
    }                                 

    private void player2MouseHover(java.awt.event.MouseEvent evt) {                                   
        // TODO add your handling code here:
        changeImage(btPlayer2, "player2Hover");
        setTooltipforButton(btPlayer2, "Play game with 2 players mode");
    }                                  

    private void player2MouseExit(java.awt.event.MouseEvent evt) {                                  
        // TODO add your handling code here:
        changeImage(btPlayer2, "player2");

    }                                 

    private void ruleHover(java.awt.event.MouseEvent evt) {                           
        // TODO add your handling code here:
        changeImage(btRule, "ruleHover");
        setTooltipforButton(btRule, "Play this game with this rule");
    }                          

    private void ruleMouseExit(java.awt.event.MouseEvent evt) {                               
        // TODO add your handling code here:
        changeImage(btRule, "rule");
    }                              

    private void AboutMouseHover(java.awt.event.MouseEvent evt) {                                 
        // TODO add your handling code here:
        changeImage(btAbout, "aboutHover");
        setTooltipforButton(btAbout, "About Me!!!!");
    }                                

    private void AboutMouseExit(java.awt.event.MouseEvent evt) {                                
        // TODO add your handling code here:
        changeImage(btAbout, "about");
    }                               

    private void enterAboutPanel(java.awt.event.MouseEvent evt) {                                 
        // TODO add your handling code here:
        jDesktopRemoveAndRepaint();
        CallPanel(aboutPanel);

    }                                

    public void jDesktopRemoveAndRepaint(){
        jDesktopPane1.removeAll();
        jDesktopPane1.repaint();
        jDesktopPane1.revalidate();
    }

    public void CallPanel(JPanel panel){
        panel.setBounds(0, 0, 840, 558);
        panel.setSize(840,558);
        jDesktopPane1.add(panel);
        panel.show();
    }

    private void enterToPlay1PlayerMode(java.awt.event.MouseEvent evt) {                                        
        try {
            // TODO add your handling code here:
            c = new ConnectionTCP(serverAddress);
            onePlayerMode = new onePlayer(serverAddress);
            jDesktopRemoveAndRepaint();
            CallPanel(onePlayerMode);
            c.getOut().println("onePMode");


        } catch (Exception ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                       

    private void btPlayer2ActionPerformed(java.awt.event.ActionEvent evt) {                                          
       try {
            // TODO add your handling code here:
            c = new ConnectionTCP(serverAddress);           
            twoPlayerMode = new twoPlayers(serverAddress);
            jDesktopRemoveAndRepaint();

            String fromServer = c.getIn().readLine();


            c.getOut().println("twoPMode");
            twoPlayerMode.setPlayerID(fromServer);

            CallPanel(twoPlayerMode);





        } catch (Exception ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                         

    // Variables declaration - do not modify                     
    private javax.swing.JButton btAbout;
    private javax.swing.JButton btExit;
    private javax.swing.JButton btPlayer1;
    private javax.swing.JButton btPlayer2;
    private javax.swing.JButton btRule;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

Panel 2 players

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

import srpclient.player1.*;
import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import srpclient.ConnectionTCP;

/**
 *
 * @author Kency
 */
public final class twoPlayers extends javax.swing.JPanel {

    /**
     * Creates new form onePlayer
     */
    ConnectionTCP conn;
    int countWrongLetter = 0;
    String getWord = "getWord";
    String serverAddress = "";
    JLabel lblKeyword[];
    String keyword = "";
    JLabel head  = new JLabel("");
     String sHead = "", sLeft_eye="", sRight_eye="", sBody="",
            sMouth="",sLeft_arm="",sRight_arm="",sLeft_leg="",sRight_leg="";
    Graphics g;
    String playerID = "";

    public String getPlayerID() {
        return playerID;
    }

    public void setPlayerID(String playerID) {
        this.playerID = playerID;
    }
    public twoPlayers(String serverAddress) {
        try {
            initComponents();
            jTextArea1.setEditable(false);
            conn = new ConnectionTCP(serverAddress);
            this.serverAddress = serverAddress;
            conn.getOut().println("twoPMode");

            if (conn.getIn().readLine() != null) {
                setPlayerID(conn.getIn().readLine());

                System.out.println(getPlayerID());
            }
            if(getPlayerID().equals("002")){
                jButton1.setEnabled(false);
                btPlay.setEnabled(false);
            }

        } catch (IOException ex) {
            Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void getWordLabels(String keyword) {
        int length = keyword.length();
        lblKeyword = new JLabel[length];
        int widhLebelKeyword = 100;
        int heightLabelKeyword = 20;
        int gapbetweenLetter = 350/length;

        for (int i = 0; i < length; i++) {          

            lblKeyword[i] = new JLabel("_");
            jLabel1.revalidate();
            jLabel1.repaint();
            lblKeyword[i].setForeground(Color.white);
            lblKeyword[i].setBounds((gapbetweenLetter * i + 100), 300, widhLebelKeyword, heightLabelKeyword);
            jLabel1.add(lblKeyword[i]);
        }
    }








     enum BodyPart { 
            Head,
            Left_Eye,
            Right_Eye,
            Mouth,
            Body,
            Left_Arm,
            Right_Arm,
            Left_Leg,
            Right_Leg
        }


      void DrawBodyPart(BodyPart bp)
        {
            Graphics g = this.getGraphics();
            g.setColor(Color.white);

            if(bp == BodyPart.Head)// draw a head
            {
                 g.drawOval(570, 160, 70, 70);
            }else if(bp == BodyPart.Left_Eye){
                g.drawLine(580, 180, 590, 185);
                g.drawLine(590, 180, 580, 185);
            }else if(bp == BodyPart.Right_Eye){
                g.drawLine(620, 180, 630, 185);
                g.drawLine(630, 180, 620, 185);
            }else if(bp ==BodyPart.Mouth){
                g.drawArc(575, 200, 60, 50, 45, 90);
            }else if(bp == BodyPart.Body){
                 g.drawLine(605, 230, 605 , 310);
            }else if(bp == BodyPart.Left_Arm){
                 g.drawLine(550, 260, 605, 230 );
            }else if(bp == BodyPart.Right_Arm){
                g.drawLine(660, 260, 605, 230 );
            }else if(bp == BodyPart.Left_Leg){
                 g.drawLine(550, 350, 605, 310 );
            }else if(bp == BodyPart.Right_Leg){
                g.drawLine(605, 310, 660, 350 );     
            }

        }




    //get Keyword from server
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:

            conn.getOut().println(getWord);
            String inputFromServer = conn.getIn().readLine();
            System.out.println(inputFromServer);
            keyword = inputFromServer;
            getWordLabels(keyword);
            jButton1.setEnabled(false);
        } catch (IOException ex) {
            Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    //compare letter with word, if contain show it on jlabel
    private void searchLetter(){
        String  let = txtLetter.getText();
        char letter = let.toCharArray()[0];
        int length = keyword.length();
        lblKeyword = new JLabel[length];
        int widhLebelKeyword = 100;
        int heightLabelKeyword = 20;
        int gapbetweenLetter = 350/length;


        if(keyword.contains(let)){
            char[] letters = keyword.toCharArray();
            for(int i = 0 ; i < letters.length; i++){
            lblKeyword[i] = new JLabel("_");
            //jLabel1.revalidate();
            jLabel1.repaint();
            lblKeyword[i].setForeground(Color.white);
            lblKeyword[i].setBounds((gapbetweenLetter * i + 100), 300, widhLebelKeyword, heightLabelKeyword);

                if(letters[i] == letter)            {

                    lblKeyword[i].setText(Character.toString(letter));
                     jLabel1.add(lblKeyword[i]);
                }
            }
        }
    }

    //wrong letter not contain in keyword will keep in board to remind gamer which letter is wrong
    private void wrongLetter(){

        String wrongLetter = txtLetter.getText();
        String wrongLetterLabel = jLabel4.getText();
        String showWrongLetter ="";
        if(wrongLetterLabel == null){
           showWrongLetter = wrongLetterLabel + " " + wrongLetter;
        }else{
             showWrongLetter = wrongLetterLabel + ", " + wrongLetter;
        }
        jLabel4.setText(showWrongLetter);
        System.out.println(jLabel4.getText());

    }

    private void drawHangman(){
          if(countWrongLetter == 1){
               DrawBodyPart(BodyPart.Head);
           }else if(countWrongLetter == 2){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
           }else if(countWrongLetter == 3){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
           }else if(countWrongLetter == 4){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
           }else if(countWrongLetter == 5){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
               DrawBodyPart(BodyPart.Body);
           }else if(countWrongLetter == 6){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
               DrawBodyPart(BodyPart.Body);
               DrawBodyPart(BodyPart.Left_Arm);
           }else if(countWrongLetter == 7){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
               DrawBodyPart(BodyPart.Body);
               DrawBodyPart(BodyPart.Left_Arm);
               DrawBodyPart(BodyPart.Right_Arm);
           }else if(countWrongLetter == 8){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
               DrawBodyPart(BodyPart.Body);
               DrawBodyPart(BodyPart.Left_Arm);
               DrawBodyPart(BodyPart.Right_Arm);
               DrawBodyPart(BodyPart.Left_Leg);
           }else if(countWrongLetter == 9 ){
               DrawBodyPart(BodyPart.Head);
               DrawBodyPart(BodyPart.Left_Eye);
               DrawBodyPart(BodyPart.Right_Eye);
               DrawBodyPart(BodyPart.Mouth);
               DrawBodyPart(BodyPart.Body);
               DrawBodyPart(BodyPart.Left_Arm);
               DrawBodyPart(BodyPart.Right_Arm);
               DrawBodyPart(BodyPart.Left_Leg);
               DrawBodyPart(BodyPart.Right_Leg);
           }
    }

    private void btLetterActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            String letter = txtLetter.getText();
            conn.getOut().println(letter);
            String inputFromServer = conn.getIn().readLine();
            System.out.println(inputFromServer);
            if(inputFromServer.equals("containt")){

                searchLetter();
                  drawHangman();
            }else{
                wrongLetter();
                countWrongLetter++;

                System.out.println(countWrongLetter);
                drawHangman();
            }


        } catch (IOException ex) {
            Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                        

    private void btReadyActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        System.out.println(getPlayerID());
    }                                       

    // Variables declaration - do not modify                     
    private javax.swing.JButton btLetter;
    private javax.swing.JButton btPlay;
    private javax.swing.JButton btReady;
    private javax.swing.JButton btSendChat;
    private javax.swing.JButton btWord;
    private javax.swing.JButton jButton1;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField txtLetter;
    private javax.swing.JTextField txtWord;
    // End of variables declaration                   
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T21:57:55+00:00Added an answer on May 30, 2026 at 9:57 pm

    You are creating a new gameHandle object for every client, so they all see the initial playerID as “000”. From your description you need to share a single instance of that class between all clients.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Like the question says. After a solver.solve(); I want to see specific rules (with
I'm trying to solve a problem I've got where a child process runs execvp()
After reviewing A LOT of questions and Internet data, I've solved a problem of
After my last question was solved the JSON I'm receiving from the server changed
After deploying WCF server (svc) on my Server, I have got this message when
After discovering about Javascript namespaces, I tried to implement them but I run into
I have a problem that I really cannot figure out how to solve. I
I am facing a WinForm destroyal problem after the thread finishes as shown below,
can anyone help me to solve my problem, I've to make the alarm goes
Please, see this answer to see the main problem . How can you solve

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.