Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
i have this code for hangman game i want to make the button of letter disappear after i click on it. actually, i could make the button disappear; i tried whit A button. but the problem come when i restart the game it doesn't disappear

Java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.net.URL;
import java.awt.image.*;
import java.io.*;
import javax.swing.JOptionPane;
import javax.swing.border.Border;

public class HangMan extends JApplet implements ActionListener,Runnable{
    
	static HangMan applet;
	  static Thread myThread;
	
	public static void main(String[] args){
     JFrame frame =new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Hangman");
        frame.setLocation(300,50);
       applet = new HangMan();
       myThread = new Thread(applet);
        applet.init();
        frame.getContentPane().add(applet);
        frame.pack(); 
        frame.setVisible(true);
       
        }  
	 
      int delay;        
      static final int MAX=10;  // Maximum number of try outs
      public int errors;   //amount of errors
      public String msg;   // to show a message to the user 
      public String ranWord;    // get the random word
      public String hintword;   
      public int hint;
      public StringBuffer gWord;   // Guessed word
      public JButton Hint;
      public Font font= new Font("Monospaced",Font.BOLD,16);
      HMpanel panel = new HMpanel();
      JPanel p ;
      public static JButton[] butArray =  new JButton[26];
      boolean [] visable = new boolean[26];
      public static String[] alpha=  {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

  
	public void init(){ 
		for(int i=0;i<26;i++)
			visable[i]=true;
     delay = 500;   
     hint=0;   
     p = new JPanel();  //button panel
     JPanel m = new JPanel(); //menu panel
     m.setBackground(new Color(222,200,66));
     m.setForeground(new Color(222,0,0));
     p.setLayout(new GridLayout(3,10,0,1));
     
      for(int i=0;i<butArray.length;i++){
        butArray[i]= new JButton(alpha[i]);
        p.add(butArray[i]);
        butArray[i].setBackground(new Color(222,200,3));
        butArray[i].setForeground(new Color(222,0,0));
        butArray[i].addActionListener(this);
        
       // butArray[i].setText(alpha[i]);
       // butArray[i].setBorder(BorderFactory.createEmptyBorder());
        //butArray[i].setContentAreaFilled(true);
        //butArray[i].setBorderPainted(false);
        
       // ImageIcon icon = new ImageIcon("A.gif");
        
       // butArray[i].setIcon(icon);
        // butArray[i].setDisabledIcon(icon);
      // butArray[i].setPressedIcon(icon);
      }

     //JButton jb=new rJButton("Me : Lama Click");
     
     //p.add(jb);

      Hint = new JButton ("Hint");  p.add(Hint); 
      Hint.addActionListener(this);
      
     JMenuBar menubar =new JMenuBar();
     JMenu gameMenu =new JMenu("Game");
     JMenuItem restart =new JMenuItem("Restart");
     JMenuItem help =new JMenuItem("Help");
     JMenuItem about =new JMenuItem("About");
     JMenuItem quit =new JMenuItem("Quit");
     
     menubar.add(gameMenu);
     gameMenu.add(restart);
     gameMenu.addSeparator();
     gameMenu.add(help);
     gameMenu.add(about);
     gameMenu.addSeparator();
     gameMenu.add(quit);
     
     restart.addActionListener(this);
     help.addActionListener(this);
     about.addActionListener(this);
     quit.addActionListener(this);
     m.setLayout(new BorderLayout());
     m.add(menubar,BorderLayout.WEST);
     
     this.getContentPane().setLayout(new BorderLayout());
     this.getContentPane().add(p,BorderLayout.SOUTH);
     this.getContentPane().add(m,BorderLayout.NORTH);
     this.getContentPane().add(panel,BorderLayout.CENTER);
     
       errors=0;
       msg=new String("You Have No Mistakes..Good Luck!");
        String [] str={"computer","calculator","president","politics","puzzle","kitchen","language","ghost","solution","security","championship",
                       "rectangle","design","september","australia","chocolate","hippopotamus","tooth","magenta","jamaica","blanket","direction",
                       "salt","aerobics","lazy","dishonest","impressive","snow","umbrella","victim","schedules","fall","sofa","italy",
                       "travel","tennis","sky","glue","glow","illegal","technology","island","safety","beat","brazil","band","happy","friend",
                       "queen","blood","lost","shoot","hotel","interview","air","apple","tomato","whale","dream","cave","islam","brain","ill",
                       "irregular","baby","music","smile","chef","moon","blueberry","cheese","knife","movie","economy","bride","result","ink",
                       "honey","oxygen","cousin","singer","stupid","laugh","freeze","jar","vitamin","vacation","dangerous","punctuation",
                       "cotton","trash","earth","neptune","volcano","earthquake","humidity","zebra","giraffe","mosoquito","slim","curly","red",
                       "safari","sunday","shutter","cartoon","mistake","monitor","daughter","tuna","modem","homeless","highlight","wood"};
                       
       String [] hints={"an important invention","to calculate faster","leader of a company or country","the art or science of government",
            "a game designed to test knowledge","where you cook your food","communication through a system of signals,words",
            "a myth, spirit of a dead person", "answer","protection","a contest for the position of champion","not a square!",
            "to create according to plan","the 9th month","the smallest continent","our favorite candy","a large,semi aquatic animal",
            "you bite with your?","purple","an island country in the Caribbean Sea","a piece of fabric used for warmth","path,way",
            "to season & give flavor","exercises for the heart and lungs","not active nor energetic","lie,cheat",
            "good impression causing admiration","form of small white ice crystals","a must have when raining","a casualty","timetables",
            "drop by the force of gravity","couch","home of pizza & pasta","going from a place to another","A sport played by pairs",
            "the upper atmosphere as seen from earth","to stick things together","shine brightly","against the law",
            "application of science for industrial objectives","A piece of land surrounded by water","prevent injury or damage","hit",
            "the largest country in South America","a group of musicians","pleasure or joy","a person who one knows, loves & trusts",
            "a king's wife","red fluid in the vascular system","not found","discharge","where travlers stay","a formal meeting",
            "invisible gas(78%=N,21%=O)","the mac fruit","is it a vegetable or fruit?","the largest marine mammal",
            "series of thoughts during sleep","a hole in a mountain","the fastest growing religion","the center of the nervous system","sick",
            "a contrary to rules","a very young child(infant)","vocal, instrumental sounds having rhythm","a pleased facial expression",
            "a professional cook","the earth's natural satellite, visible at night","a small, sweet berry","food made from the pressed curds of milk",
            "A cutting tool composed of a blade & a handle","a motion picture","the wealth & resources of a country",
            "a woman just or about to be married","outcome","a colored fluid used for writing","a sweet fluid made by bees",
            "essential gas for respiration","a person belonging to the same family","a professional vocalist","unintelligent,dumb",
            "show  joy with a vocal sound","solidify by loss of heat","container","organic compound essential for growth & nutrition","holiday",
            "unsafe","marks used in writing to clarify meaning","soft white fibrous substance","garbage","our planet","The 8th planet from the sun",
            "a hole which lava, ash & gases are ejected from","sudden and violent shaking of the ground",
            "the amount of water in the air","a striped animal","an animal with the longest neck","the female flies bites are bloodsucking",
            "thin","arranged in curves","the color of blood","trip to watch animals in their habitat","2nd day of the week",
            "A movable cover for a window or door","a drawing of an object","error","screen","a female offspring","the most popular eaten fish",
            "A device for converting digital data & analog signals","a person without a home","pick out and emphasize",
            "The hard material extracted from a tree"};
       
                    
                       Random ran = new Random();
                       int intRan = (int) (Math.floor(Math.random()*(str.length-0+1))+1);
                       ranWord= new String(str[intRan]);
                       System.out.println(ranWord);
                       char pos[]=new char[ranWord.length()];
                       for(int i= 0; i <ranWord.length() ;i++)
                           {pos[i]='*'; }
                         String s= new String(pos);
                      gWord= new StringBuffer(s); 
                       hintword= new String(hints[intRan]);}

public void run(){
	 while (myThread != null ) 
     {		for(int i=0;i<26;i++)
    	 			butArray[i].setVisible(visable[i]); 
     repaint(); 
     
      try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
      if ( myThread==null ) 
      { 
      myThread = new Thread(applet); 
     // applet.init();
      } 
          
}}
	public void actionPerformed (ActionEvent e){
          
          String action = e.getActionCommand();
          char EL ;     //the entered letter
          
          final Frame fmsg = new Frame();
             fmsg.setBackground(Color.WHITE);
             TextArea ta = new TextArea();
             ta.setRows(7);
             ta.setEditable(false);
             fmsg.setLocation(500,300);
        
        
           if (action.equals("Help")) {
                  fmsg.setTitle("HELP");
                  String textToApper = "To Win The Hangman Game You Must Correctly Guess All The Letters\n Of The Hidden Word"+
                  "\n\n"+"Good Luck";
              ta.append(textToApper);
             // fmsg.getContentPane().add(ta);
             fmsg.add(ta);
              fmsg.pack();
              fmsg.setVisible(true);
              
              fmsg.addWindowListener(new WindowAdapter(){
                 public void windowClosing(WindowEvent we){
                //System.exit(0);
                 fmsg.dispose();
                 }
                  });
                   } 
                    
           else if (action.equals("About")) {
                 fmsg.setTitle("About Hang-Man");
                  String textToApper = "Developed By: Lama Rouzi, Haneen Kassim And Sara Turkistani";
              ta.append(textToApper);
            //  fmsg.getContentPane().add(ta);
                 fmsg.add(ta);
              fmsg.pack();
              fmsg.setVisible(true);
              fmsg.addWindowListener(new WindowAdapter(){
                 public void windowClosing(WindowEvent we){
                 fmsg.dispose();
                 }
                  });
                   }
                   
           else if (action.equals("Quit")) {
                 System.exit(0);
                   } 
                       
           else if (action.equals("Restart")) {
                 //int response = JOptionPane.showConfirmDialog(JOptionPane.getRootFrame(),
                // "Are You Sure You Want To Restart", "Restart", 1, -1);
           //switch(response) { 
            // case JOptionPane.YES_OPTION:;
        	  
        	  // butArray= new JButton[26];
        	   for(int i=0;i<26;i++)
       			{visable[i]=true;
        	  butArray[i].setVisible(true);}
        	  
        	 //  applet= new HangMan();
        	   myThread=null;
        	   init();
        	  //destroy();
        	 
        	   // this.init();
        	  //applet.stop();
        	 //  this.start();
              // break;
            // case JOptionPane.NO_OPTION: break;
             //case JOptionPane.CANCEL_OPTION: break; 
             //case JOptionPane.CLOSED_OPTION: break;
           }
           if(action.equals("Hint"))
           {hint = 1;
           }
                if(errors <10){
            if (action.equals("A")) {
            	visable[0]=false;
                        EL = 'a';
                        entLetter(EL); 
                        System.out.println("mee");
                      
                     //  if( butArray[0].isSelected());
                       //butArray[0].setVisible(visable[0]);
                       //butArray[0].removeActionListener(this);
                        
                        }
            else if (action.equals("B")) {
                        EL = 'b';
                        entLetter(EL);}
            else if(action.equals("C")){
                    EL='c';
                    entLetter(EL);}
            else if (action.equals("D")) {
                        EL = 'd';
                        entLetter(EL);}
            else if (action.equals("E")) {
                        EL = 'e';
                        entLetter(EL);} 
            else if (action.equals("F")) {
                        EL = 'f';
                        entLetter(EL);}
            else if (action.equals("G")) {
                        EL = 'g';
                        entLetter(EL);}
            else if (action.equals("H")) {
                        EL = 'h';
                        entLetter(EL);}
            else if (action.equals("I")) {
                        EL = 'i';
                        entLetter(EL);} 
            else if (action.equals("J")) {
                        EL = 'j';
                        entLetter(EL);}
            else if (action.equals("K")) {
                        EL = 'k';
                        entLetter(EL);}
            else if (action.equals("L")) {
                        EL = 'l';
                        entLetter(EL);}
            else if (action.equals("M")) {
                        EL = 'm';
                        entLetter(EL);}
            else if (action.equals("N")) {
                        EL = 'n';
                        entLetter(EL);} 
            else if (action.equals("O")) {
                        EL = 'o';
                        entLetter(EL);}
            else if (action.equals("P")) {
                        EL = 'p';
                        entLetter(EL);}
            else if (action.equals("Q")) {
                        EL = 'q';
                        entLetter(EL);}
            else if (action.equals("R")) {
                        EL = 'r';
                        entLetter(EL);}
            else if (action.equals("S")) {
                        EL = 's';
                        entLetter(EL);} 
            else if (action.equals("T")) {
                        EL = 't';
                        entLetter(EL);}
            else if (action.equals("U")) {
                        EL = 'u';
                        entLetter(EL);}
            else if (action.equals("V")) {
                        EL = 'v';
                        entLetter(EL);}
            else if (action.equals("W")) {
                        EL = 'w';
                        entLetter(EL);}
            else if (action.equals("X")) {
                        EL = 'x';
                        entLetter(EL);}                                                                        
            else if (action.equals("Y")) {
                        EL = 'y';
                        entLetter(EL);}
            else if (action.equals("Z")) {
                        EL = 'z';
                        entLetter(EL);} }   
                                    
            }
                       
      private void entLetter(char en)
       {   if(ranWord.indexOf(en)==-1){
                        
 msg="";
                         errors++; 
                           msg="You Have "+errors+" Mistake/s";}
                                 
        if(errors==MAX){
                         msg="You Lose.. Better Luck Next Time";
                          return; 
                          }
            
        for (int i=0;i<ranWord.length();i++){
                        if(ranWord.charAt(i)==en){
                         gWord.setCharAt(i,en);
                         System.out.println(gWord);
                        }} 
                       String s=new String (gWord);
                       if(s.indexOf('*')==-1){
                        msg="Congrats,You Won"; 
                        return;
                       }}  
                                             
  class HMpanel extends JPanel {
   int y = 320;
   int e = 250;
  int L1_y = 450;
  int L2_y1 = 450;
   int L2_x2 = 400;
   int L2_y2 = 150;
   int L3_y = 150;
   int L4_y1 = 150;
   int L4_y2 = 250;
   int L5_y1 = 285;
   int L5_y2 = 330;
   int L6_y1 = 290;
   int L6_y2 = 320;
   int L7_y1 = 290;
   int L7_y2 = 320;
   int L8_y1 = 330;
   int L8_y2 = 380;
   int L9_y1 = 330;
   int L9_y2 = 380;
   BufferedImage image;
   
    
   public HMpanel(){
    setPreferredSize(new Dimension(800,500));
    setBackground(Color.white);
    URL url = getClass().getClassLoader().getResource("stk0.png");
           try {
                  image = ImageIO.read(url);
               } catch (IOException ex) {
                 ex.printStackTrace();
                 }
     }
   
   public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    
    Stroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER);
    g2.setStroke(stroke);
    g2.drawImage(image, 0, 0,800,500, this);
    
    Ellipse2D elp=new Ellipse2D.Double(530,250,40,35);
    Line2D line1 = new Line2D.Double(380,450,700,450); 
    Line2D line2 = new Line2D.Double(400,450,400,150);
    Line2D line3 = new Line2D.Double(400,150,570,150);
    Line2D line4 = new Line2D.Double(550,150,550,250); 
    Line2D line5 = new Line2D.Double(550,285,550,330);
    Line2D line6 = new Line2D.Double(550,290,575,320); 
    Line2D line7 = new Line2D.Double(550,290,525,320);
    Line2D line8 = new Line2D.Double(550,330,580,380); 
    Line2D line9 = new Line2D.Double(550,330,520,380);
    Line2D line10 = new Line2D.Double(550,290,575,y); 
    Line2D line11 = new Line2D.Double(550,290,525,y);

    Ellipse2D elp11=new Ellipse2D.Double(530,e,40,35);
    Line2D line111 = new Line2D.Double(380,L1_y,700,L1_y); 
    Line2D line211 = new Line2D.Double(400,L2_y1,L2_x2,L2_y2);
    Line2D line311 = new Line2D.Double(400,L3_y,570,L3_y);
    Line2D line411 = new Line2D.Double(550,L4_y1,550,L4_y2); 
    Line2D line511 = new Line2D.Double(550,L5_y1,550,L5_y2);
    Line2D line611 = new Line2D.Double(550,L6_y1,575,L6_y2); 
    Line2D line711 = new Line2D.Double(550,L7_y1,525,L7_y2);
    Line2D line811 = new Line2D.Double(550,L8_y1,580,L8_y2); 
    Line2D line911 = new Line2D.Double(550,L9_y1,520,L9_y2);
    
    repaint();
    
    if(errors>0)
     {g2.setColor(new Color(153,204,0)); 
     g2.draw(line1);} 
    if(errors>1)
     {g2.setColor(new Color(99,44,3)); 
     g2.draw(line2);}  
    if(errors>2)
     {g2.draw(line3);} 
    if(errors>3)
     {g2.setColor(new Color(255,153,0)); 
     g2.draw(line4);}  
    if(errors>4)
     {g2.setColor(Color.black);
     g2.fill(elp);} 
    if(errors>5)
     {g2.draw(line5);}  
    if(errors>6)
     {g2.draw(line6);}        
    if(errors>7)
     {g2.draw(line7);}
    if(errors>8)
     {g2.draw(line8);}
    if(errors>9)
     {g2.draw(line9);}
    
    if(msg=="Congrats,You Won"){
     try {
         Thread.sleep (delay);} 
          catch (InterruptedException e) {}  
     errors=0;
     g2.setColor(Color.black);
     g2.fill(elp);
          g2.draw(line5);
          g2.draw(line10);
            g2.draw(line11);
          g2.draw(line8);
          g2.draw(line9);
          y-=40;
            if (y < 280) y = 320;
            repaint();}
            
          if(msg=="You Lose.. Better Luck Next Time") {
           try {
         Thread.sleep (delay);} 
       catch (InterruptedException e) {}
           errors=0;
           g2.setColor(new Color(153,204,0)); 
     g2.draw(line111);
     g2.setColor(new Color(99,44,3)); 
     g2.draw(line211);
     g2.draw(line311);
     g2.setColor(new Color(255,153,0)); 
     g2.draw(line411);
     g2.setColor(Color.black);
     g2.fill(elp11);
     g2.draw(line511);
     g2.draw(line611);
     g2.draw(line711);
     g2.draw(line811);
     g2.draw(line911);
     e+=50;
         L1_y+=5;
         L2_y1+=50;
         L2_x2+=50; 
        
 L2_y2+=50;
         L3_y+=60;
         L4_y1+=30;
         L4_y2+=30;
         L5_y1+=60;
         L5_y2+=60;
         L6_y1+=80;
         L6_y2+=80;
           L7_y1+=60;
         L7_y2+=60;
         L8_y1+=50;
         L8_y2+=50;
         L9_y1+=20;
         L9_y2+=20;
         repaint(); 
          }

    //show msg
    
    g2.setColor(new Color(0,102,153));
    g2.setFont(new Font("Monospaced",Font.BOLD,18));
   g2.drawString(msg,20,305);
   g2.drawString("Secret Word Is:",10,109);
   g2.setColor(new Color(200,0,0));
   g2.setFont(new Font("Monospaced",Font.BOLD,26));
    g2.drawString(new String(gWord),180,109);
    
    g2.drawString("Hang Man",330,59);
    if(hint==1){
    g2.setFont(new Font("Monospaced",Font.BOLD,15));
    g2.drawString(hintword,10,405);}
    
   }}}
Posted

1 solution

not bad!

The action for the buttons takes place in this function:
Java
private void entLetter(char en) {   
	if(ranWord.indexOf(en)==-1){
		msg="";
		errors++; 
		msg="You Have "+errors+" Mistake/s";}
	
	if(errors==MAX){
		msg="You Lose.. Better Luck Next Time";
		return; 
	}
	
	for (int i=0;i<ranword.length();i++){>
		if(ranWord.charAt(i)==en){
			gWord.setCharAt(i,en);
			System.out.println(gWord);
		}} 
	String s=new String (gWord);
	if(s.indexOf('*')==-1){
		msg="Congrats,You Won"; 
		return;
	}
}  


You need to identify the button and deactivate it. The button is actually given by the event (event.getSource()). Pass that information to your entLetter(Char en) method and let it there the button be disabled. After that you need to update your Button JPanel to make the change visible.

EDIT:

Java
else if (action.equals("B")) {
                       EL = 'b';
                       entLetter(EL);}
           else if(action.equals("C")){
                   EL='c';
                   entLetter(EL);}
         // *snip*
           else if (action.equals("X")) {
                       EL = 'x';
                       entLetter(EL);}
           else if (action.equals("Y")) {
                       EL = 'y';
                       entLetter(EL);}
           else if (action.equals("Z")) {
                       EL = 'z';
                       entLetter(EL);} }

           }


NO!
- get String
- String.toLowerCase() returns small letter

you should refactor some.
 
Share this answer
 
v2
Comments
Sandeep Mewara 15-May-12 5:44am    
My 5!
TorstenH. 15-May-12 5:56am    
thx.

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