Results 1 to 7 of 7
  1. #1
    MetalR0 is offline Member
    Join Date
    Jul 2011
    Posts
    23
    Rep Power
    0

    Default N o Action by ActionListener

    I am trying to make a working GUI. For some reason when I run it NONE of the buttons perform the actions I outline in Action Listener. What am I doing wrong? Have updated with all classes involved with a [c*de] at beginning of the first and [/c*de] at end of last. The if statements in the ActionListner class are being reached when a button is hit but the code within the matching if statement is not. What gives?!?!?!?

    Java Code:
    public class MyClass extends JFrame implements ActionListener
    {
    	
    	private static final long serialVersionUID = 5688321467161421359L;
    	/**
    	 * Grid of square buttons
    	 */
    	private JPanel[][] squares;
    	/**
    	 * Polymorphed instance of the ConnectFour class
    	 */
    	private static BoardGame myGame = new ConnectFour();
    	/**
    	 * New Game Button
    	 */
    	private JButton btnNewGame;
    	/**
    	 * Quit Button
    	 */
    	private JButton btnQuit;
    	/**
    	 * Single row of buttons lining top of playing grid
    	 */
    	private JButton[] drops;
    	/**
    	 * Variable that increments with every turn
    	 */
    	private int counter = 2;
    	/**
    	 * String message indicating current status of game
    	 */
    	private String state = "Click drop button above a column to place chip";
    	/**
    	 * Constructor which intializes GUI and all aforementioned buttons,panels,arrays
    	 * etc.  
    	 */
    	public MyClass()
    	{
    		setSize(500,550);
    		setTitle("Game");
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		
    		Container c = getContentPane();
    		btnNewGame = new JButton("New Game");
    		JButton btnQuit = new JButton("Quit");
    		JLabel status = new JLabel(state);
    		JPanel C4board = new JPanel();
    		JPanel top = new JPanel();
    		JPanel bottom = new JPanel();
    		drops = new JButton[7];
    		bottom.setLayout(new GridLayout(3,1));
    		c.add(top,BorderLayout.NORTH);
    		top.setLayout(new GridLayout(1,7));
    		c.add(bottom,BorderLayout.SOUTH);
    		btnNewGame.addActionListener(this);
    		btnQuit.addActionListener(this);
    		for (int d = 0; d < drops.length; d++) {
    			drops[d] = new JButton("DROP");
    	        drops[d].addActionListener(this);
    	        drops[d].setPreferredSize(new Dimension(5, 20));
    	        top.add(drops[d],BorderLayout.NORTH);
    	    }
    		squares = new JPanel[6][7];
    		for(int r = 0; r < squares.length; r++) {
    			for (int col = 0; col < squares[r].length; col++) {
    				squares[r][col] = new JPanel();
    				C4board.add(squares[r][col]);
    				squares[r][col].setPreferredSize(new Dimension(66, 60));
    			}
    		}	
    		
    		bottom.add(btnNewGame, BorderLayout.SOUTH);
    		bottom.add(btnQuit, BorderLayout.SOUTH);
    		bottom.add(status,BorderLayout.SOUTH);
    		c.add(C4board, BorderLayout.CENTER);
    		C4board.setBackground(Color.yellow);
    		
    
    		setVisible(true);
    
    	}
    	/**
    	 * Displays text on Jpanel indicating game status.
    	 */
    /**
     * Method determines what happens when each button is clicked
     */
    	public void actionPerformed(ActionEvent e) {
    		if (e.getSource().equals(btnNewGame)) {
    			myGame.newGame();
    		}
    		
    		if(e.getSource().equals(btnQuit)) {
    					System.exit(0);
    		}
    		for (int click = 0; click < drops.length; click++) {
    		
    		  if(e.getSource().equals(drops[click])) {
    			for(int p = 5; p >= 0; p--) {
    			  if(myGame.getBoard()[p][click] == 0){
    				 continue;
    			  }
    			  else if(whoseturn() == 1){
    				    counter++;
    					squares[p][click].setBackground(Color.red);
    			  }
    			  else if(whoseturn() == 2){
    				  	counter++;
    				  	squares[p][click].setBackground(Color.black);
    				}
    			}
    		  }
    		}
    	
    	}	
    	/**
    	 * Method returns number of player whose turn it is.
    	 * @return 1 if player 1's or 2 if player 2's.
    	 */
    	private int whoseturn() {
    		if(counter % 2 == 1){
    			return 1;
    		}
    		else {
    			return 2;
    		}
    	}
    	public static void main(String[] args)
    	{
    		myGame.newGame();
    		new MyClassDemo();
    		
    
    	}
    	
    
    
    
    
    public class C implements BGame {
    /**
     * variable that keeps track of number of moves.	
     */
    	private int counter;
    /**
     * 2D array which establishes the playing board.	
     */
    	private int board [][] = new int [6][7];
    /**
     * array keeping track of position of player 1 chips on board.
     */
    	private Position[] player1 = new Position[21];
    /**
     *  variable increments whenever Player 1 makes a move
     */
    	private int P1 = 0;
    /**
     * array keeping track of position of player 2 chips on board.
     */		
    	private Position[] player2 = new Position[21];
    /**
     *  variable increments whenever Player 1 makes a move
     */	
    	private int P2 = 0;
    /**
     * Method determines which player's turn it is.  Returns correct player #.
     * @return 1 if player 1 and 2 if player 2
     */
    	private int whoseturn() {
    		if(counter % 2 == 1){
    			return 1;
    		}
    		else {
    			return 2;
    		}
    	}
    	public void newGame() {
    		counter = 3;
    		P1 = 0;
    		P2 = 0;
    		
    		for(int m = 0; m < player1.length; m ++) {
    			player1[m]= new Position();
    			player1[m].setRow(0);
    			player1[m].setColumn(0);
    		}
    		for(int l = 0; l < player2.length; l ++) {
    			player2[l]= new Position();
    			player2[l].setRow(0);
    			player2[l].setColumn(0);
    		}
    		if(counter == 3) {
    			for(int i = 0; i < board.length; i++)
    	    	{
    	    	   for(int j = 0; j < board[i].length; j++)
    	    	   {
    	    	      board[i][j] = 0;   
    	    	   }
    	    	}
    		}
    	}	
    	public boolean gameOver() {
    		if(getWinner() == 1 || getWinner() == 2) {
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    
    	public int getWinner() {
    		int victor = 0;
    		Position[] array = new Position[4];
    		array =	getWinningPositions();
    		int a = board[array[3].getRow()][array[3].getColumn()];
    		int b = board[array[2].getRow()][array[2].getColumn()];
    		int c = board[array[1].getRow()][array[1].getColumn()];
    		int d = board[array[0].getRow()][array[0].getColumn()];
    		if(array[0].equals(array[1]) || array[0].equals(array[2]) || array[0].equals(array[3]))
    			return 0;
    		else if(a == b && b == c && c == d){
    			victor = a;
    		}
    			
    		return victor;
    		
    	}
    	public Position[] getWinningPositions(){
    		Position focus;
    		Position winspots[] = new Position[4];//array of like chips
    		Position farray[]; // P! or P2 array depending on whose turn it (decided by next code lines)
    		if(whoseturn() == 1){
    		focus = player1[0];//chip we start with
    		farray = player1;
    		}
    		else{
    			focus = player2[0];
    			farray = player2;
    		}
    		Position candidate = new Position();//chip being examined to see if same as focus
    		candidate.setRow(-1);
    		candidate.setColumn(-1);
    		
    		for(int h = 0; h < farray.length; h++){ //loop through all player chips on board	
    			
    			focus = farray[h];// sets chip as focus	
    			for(int ws = 0; ws < winspots.length; ws ++) {
    				winspots[ws]= new Position();
    			}
    				
    			if(focus.getRow() >= 0 && focus.getRow() + 3 < 6 && // falling diagonal
    					focus.getColumn() >= 0 && focus.getColumn() + 3 < 7) {
    				 if(board[focus.getRow() + 1][focus.getColumn() + 1] == whoseturn() &&
    					board[focus.getRow() + 2][focus.getColumn() + 2] == whoseturn() &&
    					board[focus.getRow() + 3][focus.getColumn() + 3] == whoseturn()){
    					Position candidate1 = new Position();
    					candidate1.setRow(focus.getRow() +1);
    					candidate1.setColumn(focus.getColumn() +1);
    					Position candidate2 = new Position();
    					candidate2.setRow(focus.getRow() + 2);
    					candidate2.setColumn(focus.getColumn() + 2);
    					Position candidate3 = new Position();
    					candidate3.setRow(focus.getRow() + 3);
    					candidate3.setColumn(focus.getColumn() + 3); 
    						 winspots[0] = focus;
    						 for(int i = 0; i < farray.length; i ++){
    							 if(farray[i].equals(candidate1))
    								 winspots[1] = farray[i];
    							 if(farray[i].equals(candidate2))
    								 winspots[2] = farray[i];
    							 if(farray[i].equals(candidate3))
    								 winspots[3] = farray[i];
    						 }
    						 return winspots;
    				}
    			}				 
    				if(focus.getRow() - 3 >= 0 && focus.getRow() < 6 && 
    						focus.getColumn() >= 0 && focus.getColumn() + 3 < 7) {//rising diagonal
    				
    				if(board[focus.getRow() - 1][focus.getColumn() + 1] == whoseturn() &&
    				   board[focus.getRow() - 2][focus.getColumn() + 2] == whoseturn() &&
    				   board[focus.getRow() - 3][focus.getColumn() + 3] == whoseturn()){
    					Position candidate1 = new Position();
    					candidate1.setRow(focus.getRow() - 1);
    					candidate1.setColumn(focus.getColumn() + 1);
    					Position candidate2 = new Position();
    					candidate2.setRow(focus.getRow() - 2);
    					candidate2.setColumn(focus.getColumn() + 2);
    					Position candidate3 = new Position();
    					candidate3.setRow(focus.getRow() - 3);
    					candidate3.setColumn(focus.getColumn() + 3); 
    						 winspots[0] = focus;
    						 for(int i = 0; i < farray.length; i ++){
    							 if(farray[i].equals(candidate1))
    								 winspots[1] = farray[i];
    							 if(farray[i].equals(candidate2))
    								 winspots[2] = farray[i];
    							 if(farray[i].equals(candidate3))
    								 winspots[3] = farray[i];
    						 }
    						 return winspots;
    					}
    				}			
    				if(focus.getRow() >= 0 && focus.getRow() <= 7 &&
    						focus.getColumn() >= 0 && focus.getColumn() + 3 < 7) {// horizontal
    				 if(board[focus.getRow()][focus.getColumn() + 1] == whoseturn() &&
    					board[focus.getRow()][focus.getColumn() + 2] == whoseturn() &&
    					board[focus.getRow()][focus.getColumn() + 3] == whoseturn()){
    					Position candidate1 = new Position();
    					candidate1.setRow(focus.getRow());
    					candidate1.setColumn(focus.getColumn() +1);
    					Position candidate2 = new Position();
    					candidate2.setRow(focus.getRow());
    					candidate2.setColumn(focus.getColumn() + 2);
    					Position candidate3 = new Position();
    					candidate3.setRow(focus.getRow());
    					candidate3.setColumn(focus.getColumn() + 3); 
    						 winspots[0] = focus;
    						 for(int i = 0; i < farray.length; i ++){
    							 if(farray[i].equals(candidate1))
    								 winspots[1] = farray[i];
    							 if(farray[i].equals(candidate2))
    								 winspots[2] = farray[i];
    							 if(farray[i].equals(candidate3))
    								 winspots[3] = farray[i];
    					 }
    						 return winspots;
    				 }
    				}			 
    				if(focus.getRow() - 3 >= 0 && focus.getRow() - 3 < 6 && 
    						focus.getColumn() >= 0 && focus.getColumn() < 7) { //vertical
    				 if(board[focus.getRow() -1][focus.getColumn()] == whoseturn() &&
    					board[focus.getRow() -2][focus.getColumn()] == whoseturn() &&
    					board[focus.getRow() -3][focus.getColumn()] == whoseturn()){
    					Position candidate1 = new Position();
    					candidate1.setRow(focus.getRow() - 1);
    					candidate1.setColumn(focus.getColumn());
    					Position candidate2 = new Position();
    					candidate2.setRow(focus.getRow() - 2);
    					candidate2.setColumn(focus.getColumn());
    					Position candidate3 = new Position();
    					candidate3.setRow(focus.getRow() - 3);
    					candidate3.setColumn(focus.getColumn()); 
    						 winspots[0] = focus;
    						 for(int i = 0; i < farray.length; i ++){
    							 if(farray[i].equals(candidate1))
    								 winspots[1] = farray[i];
    							 if(farray[i].equals(candidate2))
    								 winspots[2] = farray[i];
    							 if(farray[i].equals(candidate3))
    								 winspots[3] = farray[i];
    					 }
    						 return winspots;
    				 
    				}			 
    				else {
    					  	continue; //no possible matches of 4 in a row start w/focus.  
    				}
    				}				 
    		}			
    		return winspots;
    	}
    			
    	public boolean columnFull(int column) {
    		if(board[0][column] != 0 && counter > 5) {
    			return true;
    		}
    		else{
    			return false;
    		}
    	}
    	public void play(int column) {
    		if(gameOver()){
    			return;
    		}
    		if(columnFull(column) == false){
    			for(int i = 5; i <= 5; i--) {
    				if(board[i][column] == 0)
    				{
    					board[i][column] = whoseturn();
    					if(whoseturn() == 1){
    						player1[P1].setRow(i);
    						player1[P1].setColumn(column);
    						P1++;
    						break;
    					}
    					else if(whoseturn() == 2){
    						player2[P2].setRow(i);
    						player2[P2].setColumn(column);
    						P2++;
    						break;
    					}
    				}			
    			}
    			if(getWinner() == 0)
    			  	
    		counter++;
    			
    		}		  
    	}		
    	public int[][] getBoard() {
    		return board;
    	}
    	public String toString() {
    		String s = " ";
    		int g = 0;		
    		int k = 0;
    		for(g = 0; g < board.length;g++) {
    			for(k = 0; k < board[g].length; k++) {
    				s+= " ["  + board[g][k] + "]";
    			}
    			s+= "\n";
    		}	
    		return s;
    	}
    
    }
    
    
    
    
    public interface BGame { 
        /**
         * Prepares the board for a new game.
         */
        public void newGame();  
        
        /**
         * Is the game over?
         * @return true if the game is over, false otherwise
         */
        public boolean gameOver(); 
        
        /**
         * Who is the winner?
         * @return 0 if there is no winner, 1 if the first player is a winner, 2 if the second player is a winner.
         */
        public int getWinner(); 
        
        /**
         * Where are the tokens that determine who the winner is?
         * @return the locations of the pieces that determine the game winner.
         */
        public Position[] getWinningPositions();
        
        /**
         * Does the column have room for an additional move?
         * @param column the column number
         * @return false if there is room for another move in the column, true if not.
         */
        public boolean columnFull(int column);  
        
        /**
         * Change the game to reflect the current player placing a piece in the column.
         * @param column the column number
         */
        public void play(int column);  
        
        /**
         * What is the current board configuration?
         * @return for each cell on the board grid: 
         *   0 if it is not filled, 
    	 *   1 if it is filled by the first player's piece, 
    	 *   2 if it is filled by the second player's piece.
         */
        public int[][] getBoard();  
    }
    Last edited by MetalR0; 07-17-2011 at 08:53 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please post all the code (I'm guessing that it shouldn't be too long). Please use code tags (see my signature link).

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, you will want to add some debugging code into your program so you can test its state as it's running. Several System.out.println's should help, for instance something like this:

    Java Code:
       public void actionPerformed(ActionEvent e) {
          if (e.getSource().equals(btnNewGame)) {
             myGame.newGame();
          }
    
          if (e.getSource().equals(btnQuit)) {
             System.exit(0);
          }
          for (int click = 0; click < drops.length; click++) {
    
             if (e.getSource().equals(drops[click])) {
                
                // *** add this ***
                System.out.println("drops[" + click + "] pressed");
                
                for (int p = 5; p >= 0; p--) {
                   if (myGame.getBoard()[p][click] == 0) {
                      System.out.println("myGame.getBoard()[p][click] == 0");
                      continue;
                   } else if (whoseturn() == 1) {
                      counter++;
                      squares[p][click].setBackground(Color.red);
                      System.out.println("whoseturn() == 1. counter = " + counter);
                   } else if (whoseturn() == 2) {
                      counter++;
                      squares[p][click].setBackground(Color.black);
                      System.out.println("whoseturn() == 2. counter = " + counter);
                   }
                }
             }
          }
    
       }

  4. #4
    MetalR0 is offline Member
    Join Date
    Jul 2011
    Posts
    23
    Rep Power
    0

    Default

    Here is the repost, problem is same as befor. I didn't totally understand how to allocate the code tags. Please let me know if I did ok, if not tell me how to fix and its done. Thanks!




    public class myClass extends JFrame implements ActionListener
    {
    /**
    *
    */
    private static final long serialVersionUID = 5688321467161421359L;
    /**
    * Grid of square buttons
    */
    private JPanel[][] squares;
    /**
    * Polymorphed instance of the C class
    */
    private static BGame myGame = new C();
    /**
    * New Game Button
    */
    private JButton btnNewGame;
    /**
    * Quit Button
    */
    private JButton btnQuit;
    /**
    * Single row of buttons lining top of playing grid
    */
    private JButton[] drops;
    /**
    * Variable that increments with every turn
    */
    private int counter = 2;
    /**
    * String message indicating current status of game
    */
    private String state = "Click drop button above a column to place chip";
    /**
    * Constructor which intializes GUI and all aforementioned buttons,panels,arrays
    * etc.
    */
    [/php]
    public MyClass()
    {
    setSize(500,550);
    setTitle("Game");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container c = getContentPane();
    btnNewGame = new JButton("New Game");
    JButton btnQuit = new JButton("Quit");
    JLabel status = new JLabel(state);
    JPanel C4board = new JPanel();
    JPanel top = new JPanel();
    JPanel bottom = new JPanel();
    drops = new JButton[7];
    bottom.setLayout(new GridLayout(3,1));
    c.add(top,BorderLayout.NORTH);
    top.setLayout(new GridLayout(1,7));
    c.add(bottom,BorderLayout.SOUTH);
    btnNewGame.addActionListener(this);
    btnQuit.addActionListener(this);
    [/php]
    for (int d = 0; d < drops.length; d++) {
    drops[d] = new JButton("DROP");
    [/php]
    drops[d].addActionListener(this);
    drops[d].setPreferredSize(new Dimension(5, 20));
    top.add(drops[d],BorderLayout.NORTH);
    }
    [/php]
    squares = new JPanel[6][7];
    for(int r = 0; r < squares.length; r++) {
    for (int col = 0; col < squares[r].length; col++) {
    squares[r][col] = new JPanel();
    C4board.add(squares[r][col]);
    squares[r][col].setPreferredSize(new Dimension(66, 60));
    }
    [/php]
    }

    bottom.add(btnNewGame, BorderLayout.SOUTH);
    bottom.add(btnQuit, BorderLayout.SOUTH);
    bottom.add(status,BorderLayout.SOUTH);
    c.add(C4board, BorderLayout.CENTER);
    C4board.setBackground(Color.yellow);


    setVisible(true);

    }

    /**
    * Method determines what happens when each button is clicked
    */
    [/php]
    public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(btnNewGame)) {
    myGame.newGame();
    }
    [/php]
    if(e.getSource().equals(btnQuit)) {
    System.exit(0);
    }
    [/php]
    for (int click = 0; click < drops.length; click++) {
    [/php]
    if(e.getSource().equals(drops[click])) {
    for(int p = 5; p >= 0; p--) {
    if(myGame.getBoard()[p][click] == 0){
    continue;
    }
    [/php]
    else if(whoseturn() == 1){
    counter++;
    squares[p][click].setBackground(Color.red);
    }
    [/php]
    else if(whoseturn() == 2){
    counter++;
    squares[p][click].setBackground(Color.black);
    }
    }
    }
    }

    }
    /**
    * Method returns number of player whose turn it is.
    * @return 1 if player 1's or 2 if player 2's.
    */
    [/php]
    private int whoseturn() {
    if(counter % 2 == 1){
    return 1;
    }
    else {
    return 2;
    }
    }
    [/php]
    public static void main(String[] args)
    {
    myGame.newGame();
    new MyClass();


    }


    }

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Edit your post above please. Get rid of all your code tags as you've added them wrong. To do it correctly add [code] or [php] above the code block and [/code] or [/php] below the code block. Otherwise there's no way we can read that mess.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Close, but you've now entered unformatted code which is all left-justified and again hard to read. Again, as I suggested initially, don't post a new post but rather edit your first post that has formatted code.

    And again, add those debug statements to see what your program is doing. I'll delete your post above to clean this up, and will delete this post shortly.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 1
    Last Post: 06-30-2011, 09:49 AM
  2. Replies: 3
    Last Post: 08-19-2010, 08:27 AM
  3. How to access the ActionListener
    By jboy in forum New To Java
    Replies: 3
    Last Post: 10-15-2009, 06:04 PM
  4. Demonstrating the ActionListener
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 04-23-2008, 08:20 PM
  5. How to use KeyListener and ActionListener
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 04-23-2008, 08:19 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
  •