Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By KevinWorkman

Thread: Toggle JButton Visibility

  1. #1
    doobybug is offline Member
    Join Date
    Mar 2008
    Posts
    17
    Rep Power
    0

    Default Toggle JButton Visibility

    Hi all,

    I am trying to do a very basic memory game where I have 2 players competing at the same time.
    What I did is that I created a 2D Jbutton array for the images and another 2D Jbutton array for the back card. When a card is clicked the back card is set to visibility false and the image to visibility true.
    My problem is that this works perfectly for the 1st image clicked and then for the second i
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    public class Grid extends JFrame implements ActionListener{
        JPanel pane = new JPanel(null);
        int col;
        int row;
        ImageIcon images[];
        JButton player1cards[][];
        JButton player2cards[][];
        JButton player1Buttons[][];
        JButton player2Buttons[][];
        int player1counter = 0;
        int player2counter = 0;
        int player1score = 0;
        int player2score = 0;
        String p1chosen1;
        String p1chosen2;
        String p2chosen1;
        String p2chosen2;
        String game;
        int level;
        JLabel pl1score;
        JLabel pl2score;
        boolean p1GuessedPics[][];
        boolean p2GuessedPics[][];
         
        public Grid(int rows, int columns, int level, String game){
            super("Level "+level);
            setLocationRelativeTo(null); 
            setSize(1000,700);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            pl1score = new JLabel("Score: "+player1score);
            pl2score = new JLabel("Score: "+player2score);
            this.game = game;
            this.level = level;
            p1GuessedPics = new boolean[rows][columns];
            p2GuessedPics = new boolean[rows][columns];
            setGuessedArrays(p1GuessedPics);
            setGuessedArrays(p2GuessedPics);
            
            images = new ImageIcon[rows*columns];
            for(int i = 0; i<(images.length/2); i++){
                images[i] = new ImageIcon("Game\\"+game+"\\L"+level+"\\"+i+".jpg");
            }
            
            int c =0;
            for(int i = (images.length/2); i<images.length; i++){
                images[i] = new ImageIcon("Game\\"+game+"\\L"+level+"\\"+(c+""+c)+".jpg");
                c++;
            }
            col = columns;
            row = rows;
            player1cards = new JButton[rows][columns];
            player2cards = new JButton[rows][columns];
            fillImageArray(player1cards);
            fillImageArray(player2cards);
            setArrayBounds(player1cards, 0, 0);
            setArrayBounds(player2cards, ((col*120)+5), 0); 
            hideArray(player1cards);
            hideArray(player2cards);
            
             player1Buttons = new JButton[rows][columns];
             player2Buttons = new JButton[rows][columns];
            fillButtonArray(player1Buttons);
            fillButtonArray(player2Buttons);
            setArrayBounds(player1Buttons, 0, 0);
            setArrayBounds(player2Buttons, ((col*120)+5), 0);   
            
            
            pl1score.setBounds(5,600,50,100);
            pane.add(pl1score);
            pl2score.setBounds(((col*120)+10),600,50,100);
            pane.add(pl2score);
            
            this.add(pane);
            setVisible(true);
           
        }
        
        public void setGuessedArrays(boolean guessed[][]){
            for(int r = 0; r<row; r++){           
              for(int c= 0; c<col; c=c+1){
                  guessed[r][c] = false;
                }
            }
        }
        public void hideArray(JButton arrayImages[][]){
             for(int r = 0; r<row; r++){           
              for(int c= 0; c<col; c=c+1){
                     arrayImages[r][c].setVisible(false);
                     
              }
            }        
        }
        public void fillButtonArray(JButton arrayButton[][]){
            ImageIcon backCard = new ImageIcon("Game\\Back\\back.jpg");
            for(int r = 0; r<arrayButton.length; r++){
                for(int c = 0; c<arrayButton[r].length; c++){
                    arrayButton[r][c] = new JButton(backCard);
                }
            }
        }
        
        public void fillImageArray(JButton arrayImages[][]){
            images = shuffleArray(images);
            int i = 0;
            for(int r = 0; r<arrayImages.length; r++){
                for(int c = 0; c<arrayImages[r].length; c++){
                    arrayImages[r][c] = new JButton(images[i]);
                    i++;
                }
            }
        }
        
      
        public static ImageIcon[] shuffleArray(ImageIcon[] shuffledArray)
        {
            Random rnd = new Random();
            for (int i = shuffledArray.length - 1; i > 0; i--)
            {
                int index = rnd.nextInt(i + 1);
                // Simple swap
                ImageIcon a = shuffledArray[index];
                shuffledArray[index] = shuffledArray[i];
                shuffledArray[i] = a;
            }
            return shuffledArray;
        }
        
         
        public void setArrayBounds(JButton arrayButton[][], int wantedX, int wantedY){
            int x = wantedX;
            int y = wantedY;
            int w = 120;
            int h = 160; 
            int length = arrayButton.length;
    
            for(int r = 0; r<row; r++){           
              for(int c= 0; c<col; c=c+1){
                      arrayButton[r][c].setBounds(x,y,w,h);
                      x=x+120;
                      pane.add(arrayButton[r][c]);
                      arrayButton[r][c].addActionListener(this);
                     
              }
              y=y+160;
              x=wantedX;
            }          
        }
        
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2 = (Graphics2D) g;
            Line2D lin = new Line2D.Float(((col*120)+5), 0, ((col*120)+5),700);
             g2.setStroke(new BasicStroke(5));
            g2.draw(lin);
    
        }
        
       
        public String fixName(String name){
            String fixed = name.replace("Game\\"+game+"\\L"+level+"\\", "");
            fixed = fixed.replace(".jpg","");
            return fixed;
        }
        
        public void redrawCards(int player){
            try{
                Thread.sleep(3000);
            if(player == 1){
                for(int r = 0; r<row; r++){
                    for(int c = 0; c<col; c++){
                        if(p1GuessedPics[r][c] == false){
                            player1Buttons[r][c].setVisible(true);
                            player1cards[r][c].setVisible(false);
                        }
                    }
                }
            }else{
                  for(int r = 0; r<row; r++){
                    for(int c = 0; c<col; c++){
                        if(p2GuessedPics[r][c] == false){
                            player2Buttons[r][c].setVisible(true);
                            player2cards[r][c].setVisible(false);
                        }
                    }
                }
            }
        }catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
        }
                
        public void showCard(int player, int r, int c) {
            
            if(player == 1){
                         
                         player1Buttons[r][c].setVisible(false);
                         player1cards[r][c].setVisible(true);
                         
                         pane.validate();
                pane.repaint();
                repaint();
                         
                        }else{
                            player2Buttons[r][c].setVisible(false);
                          player2cards[r][c].setVisible(true);
                        }
                    }
    
                    
                    
         public void actionPerformed(ActionEvent ae) {
             JButton jb = (JButton)ae.getSource();
             boolean found = false;
             int p1g1r = -1;
             int p1g2r = -1;
             int p1g1c = -1;
             int p1g2c = -1;
             for(int r = 0; (r<row) && !found; r++){
              for(int c= 0; (c<col) && !found; c=c+1){
                      if(jb==player1Buttons[r][c] && player1counter!=2){
                          showCard(1, r, c);
                          
                          found = true;
                          
                          if(player1counter == 0){
                           p1chosen1 = ((ImageIcon) player1cards[r][c].getIcon()).getDescription();
                           p1chosen1 = fixName(p1chosen1);
                            System.out.println(p1chosen1);
                            p1g1r = r;
                           p1g1c = c;
                            
                          }else{
                           p1chosen2 = ((ImageIcon) player1cards[r][c].getIcon()).getDescription();
                            p1chosen2 = fixName(p1chosen2);
                             System.out.println(p1chosen2);
                             p1g2r = r;
                             p1g2c = c;
                          }
                          player1counter++;
                        }
                        if(player1counter == 2){
                            if(p1chosen1.charAt(0)==(p1chosen2.charAt(0))){
                                player1score++;
                                pl1score.setText("Score: "+player1score);
                                p1GuessedPics[p1g1r][p1g1c] = true;
                                p1GuessedPics[p1g2r][p1g2c] = true;
                                player1counter = 0;
                                
                            }else{
                                redrawCards(1);
                                player1counter = 0;
                             
                            }
                        
                      if(jb==player2Buttons[r][c]&& player2counter!=2){
                          player2Buttons[r][c].setVisible(false);
                          player2cards[r][c].setVisible(true);
                          found = true;
                          if(player2counter == 0){
                            p2chosen1 = ((ImageIcon) player2cards[r][c].getIcon()).getDescription();
                            p2chosen1 = fixName(p2chosen1);
                            p2GuessedPics[r][c] = true;
                          }else{
                            p2chosen2 = ((ImageIcon) player2cards[r][c].getIcon()).getDescription();
                            p2chosen2 = fixName(p2chosen2);
                            p2GuessedPics[r][c] = true;
                          }
                          player2counter++;
                        }
         }
    }
    }
    }
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,839
    Rep Power
    8

    Default Re: Toggle JButton Visibility

    That's a lot of code for a problem involving two JButtons. I'd recommend creating an SSCCE that specifically demonstrates the exact problem without any of that extra code.
    DarrylBurke likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    doobybug is offline Member
    Join Date
    Mar 2008
    Posts
    17
    Rep Power
    0

    Default Re: Toggle JButton Visibility

    The problem is with this method:
    public void redrawCards(int player){

    if(player == 1){
    for(int r = 0; r<row; r++){
    for(int c = 0; c<col; c++){
    if(p1GuessedPics[r][c] == false){
    player1Buttons[r][c].setVisible(true);
    player1cards[r][c].setVisible(false);
    }
    }
    }
    }else{
    for(int r = 0; r<row; r++){
    for(int c = 0; c<col; c++){
    if(p2GuessedPics[r][c] == false){
    player2Buttons[r][c].setVisible(true);
    player2cards[r][c].setVisible(false);
    }
    }
    }
    }

    }

    When it is called the first time from actionPerformed it obeys and the second time it executes as well but it does not perform the commands.

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,839
    Rep Power
    8

    Default Re: Toggle JButton Visibility

    Like I said, an SSCCE would really help narrow the problem down. You can't put a whole program together and then compile it and hope for the best. You have to take it one step at a time. Step one involves two JButtons and setting the visibility of one when you click the other. Then go from there.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    doobybug is offline Member
    Join Date
    Mar 2008
    Posts
    17
    Rep Power
    0

    Default Re: Toggle JButton Visibility

    Quote Originally Posted by KevinWorkman View Post
    Like I said, an SSCCE would really help narrow the problem down. You can't put a whole program together and then compile it and hope for the best. You have to take it one step at a time. Step one involves two JButtons and setting the visibility of one when you click the other. Then go from there.
    Hi I tried to make it more concise...so I did 2 buttons only. When both buttons are switched on they should revert to the back card. However the card[0] is not being shown when clicked. This happened when I did the else statement in the ActionListener. If I remove it, the card is shown:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    
    public class FlipCards extends JFrame implements ActionListener{
        JPanel pane = new JPanel(null);
       
        ImageIcon images[] = new ImageIcon[2];
        JButton player1cards[] = new JButton[2];    
        JButton player1Buttons[] = new JButton[2];
        
         int clickCounter = 0;
        public FlipCards(){
            super("Flip");
            setSize(1000,700);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            
                        
            for(int i = 0; i<2; i++){
                images[i] = new ImageIcon("Game\\"+"Animals"+"\\L1\\"+i+".jpg");
            }
                
            for(int i = 0; i<2; i++){
               player1cards[i] = new JButton(images[i]);
            }
            
             ImageIcon backCard = new ImageIcon("Game\\Back\\back.jpg");
             for(int i = 0; i<2; i++){
               player1Buttons[i] = new JButton(backCard);
            }
            
           
            setArrayBounds(player1cards, 0, 0);        
            setArrayBounds(player1Buttons, 0, 0); 
            hideArray(player1cards);
          
            
            this.add(pane);
            setVisible(true);
           
        }
        
       
        public void hideArray(JButton arrayImages[]){
             for(int r = 0; r<2; r++){    
                     arrayImages[r].setVisible(false);
                     
              }
            
        }
        
        
      
      
         
        public void setArrayBounds(JButton arrayButton[], int wantedX, int wantedY){
            int x = wantedX;
            int y = wantedY;
            int w = 120;
            int h = 160; 
            int length = arrayButton.length;
    
            for(int r = 0; r<2; r++){     
                      arrayButton[r].setBounds(x,y,w,h);
                      x=x+120;
                      pane.add(arrayButton[r]);
                      arrayButton[r].addActionListener(this);
                     
              }
              y=y+160;
              x=wantedX;
            }          
        
        public void redrawCards(){
            for(int i = 0; i<2; i++){
                player1cards[i].setVisible(false);
                player1Buttons[i].setVisible(true);
            }
            
        
        }
                
        public void showCard(int i) {
            System.out.println(((ImageIcon) player1cards[i].getIcon()).getDescription());
          player1Buttons[i].setVisible(false);
            player1cards[i].setVisible(true);
            
          
                    }
    
                    
                    
         public void actionPerformed(ActionEvent ae) {
              JButton jb = (JButton)ae.getSource();
              for(int i = 0; i<2; i++){
                  if(jb == player1Buttons[i] && clickCounter!=2){
                      showCard(i);
                      clickCounter++;
                    }
                  else{
                      redrawCards();
                      clickCounter = 0;
                    }
                }
            }
    
                }

  6. #6
    doobybug is offline Member
    Join Date
    Mar 2008
    Posts
    17
    Rep Power
    0

    Default Re: Toggle JButton Visibility

    I fixed the method to show the card[0] however the redrawCards() method happens so fast that it doesn't let me the see the contents of the second card. Can anyone help?

    public void actionPerformed(ActionEvent ae) {
    JButton jb = (JButton)ae.getSource();
    for(int i = 0; i<2; i++){
    if(jb == player1Buttons[i] && clickCounter!=2){
    showCard(i);
    clickCounter++;
    }
    if(clickCounter == 2){

    redrawCards();
    clickCounter = 0;
    }
    }
    }

  7. #7
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,839
    Rep Power
    8

    Default Re: Toggle JButton Visibility

    I'm really not sure what this code is supposed to do. You have a ton of extra stuff in there if all you want to do is set the visibility of a JButton. Why not start with something simpler, like this:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class Main 
    {
    
    	public static void main(String[] args) 
    	{
    
    		JFrame mainFrame = new JFrame("JButton Test");
    		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		final JButton left = new JButton("Left");
    		final JButton right = new JButton("Right");
    		
    		left.addActionListener(new ActionListener(){
    
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				right.setVisible(!right.isVisible());
    			}
    			
    		});
    		
    		right.addActionListener(new ActionListener(){
    
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				left.setVisible(!left.isVisible());
    			}
    			
    		});
    		
    
    		
    		mainFrame.add(left,BorderLayout.WEST);
    		mainFrame.add(right,BorderLayout.EAST);
    		
    		mainFrame.setSize(200 ,100);
    		mainFrame.setVisible(true);
    
    	}
    }
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. toggle button
    By gbonecapone in forum New To Java
    Replies: 6
    Last Post: 06-06-2013, 05:49 PM
  2. Replies: 1
    Last Post: 12-17-2010, 05:01 PM
  3. Toggle Trobble
    By pottsmgg in forum New To Java
    Replies: 22
    Last Post: 09-20-2010, 04:25 PM
  4. Replies: 2
    Last Post: 04-19-2009, 05:39 AM
  5. [SOLVED] Toggle Mouse Left-Right Handed
    By sirwiggles in forum New To Java
    Replies: 4
    Last Post: 04-10-2009, 10:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •