Welcome to Dream.In.Code
Become a Java Expert!

Join 149,489 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,283 people online right now. Registration is fast and FREE... Join Now!




Action Listener Help

 
Reply to this topicStart new topic

Action Listener Help, Just need a quick Tip to get back on the ball

Suspect1
22 Mar, 2007 - 09:00 PM
Post #1

New D.I.C Head
*

Joined: 19 Mar, 2007
Posts: 6


My Contributions
Ok i'm writing a program for a tic tac toe program now in the part of "private class ButtonListener implements ActionListener" i believe is where i'm having the problem with my ActionListener normaly i'm noticing you write an action listener like addActionListener(this). But i'm having problems with the ActionListener being a private class.

for this part
//ActionListener buttonListener = new ActionListener();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3, 3));

JButton but1 = new JButton("but1");
but1.addActionListener(new buttonListener());
buttonPanel.add(but1);

what should i be putting in but1.addactionlistener( ????);

CODE
/**
* TicTacToe.java
*
* This applet uses Swing to play a simple game of Tic Tac Toe
* (noughts and crosses).  It uses a GridLayout of JButton's to
* play the game.  Each JButton has its own ButtonListener class
* that updates an internal 2D game board and checks to see if the
* game is over.
* Applets do not have security permissions to exit, so when the
* game is over a flag is set to indicate that no further play
* should occur.
*/
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JApplet;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// . . .         The . . . mean one or more lines missing - here or
//                anywhere else in the program.

/**
* TicTacToe GUI to play the game
*/
public class TicTacToe extends JApplet
{
    public static final int WIDTH = 300;
    public static final int HEIGHT = 300;
    // Dimensions of the game board, must be square
    public static final int BOARDSIZE = 3;
    public JTextArea sourceText;

    // Current player's turn, either X or O
    private char whoseturn;
    // 2D array to store pieces placed on the board, ' ', 'X', 'O'
    private char[][] board;
    // Indicates if the game is over or not, if over do nothing on button click
    private boolean gameOver;
    // Label to display messages to the players
    private JLabel messageLabel;

    /**
    * This class is the ActionListener for one of the button clicks.
    * The constructor takes the X and Y coordinate for the entry in
    * the game board that corresponds to where this button is located.
    */
   private class ButtonListener implements ActionListener
    {
        private int x,y;    // Coordinate on the game board for this button
        JButton but;        // Reference to the JButton object for this
        JButton but1;                    // ActionListener

        /**
        * The constructor stores references to the caller and the game object.
        * @param x  X coordinate on the game board for this button
        * @param y  Y coordinate on the game board for this button
        * @param but  The actual button object so we can change the text
        * @param game  The game object so we can check for a win and update
        * the board
        */
        buttonListener(int x, int y, JButton but)
        {
        
        }

        /**
        * The actionPerformed event is invoked when a button is clicked.
        * Check to see if the cell that corresponds to this button is clear;
        * if not it is an invalid move.  If clear, put a piece there, update
        * the button text with the piece label, update the game board, and
        * see if someone won.
        */
        public void actionPerformed(ActionEvent e)
        {
        if(actionCommand.equals("but1"))
        {
            System.exit(0);
        }
            // Check to see if the game is over
            //...

            // Check to see if the cell is occupied
            //...
            // Otherwise put a piece there
            //...
        }
   }

    /**
    * The init method creates the JFrame and adds 9 JButtons to the grid layout.
    * A 2D board array is also set up with the pieces that are placed;
    * initially it is blank. The action listener is created using the
    * ButtonListener class described above.
    */
    public void init()
    {
        JPanel sourcePanel = new JPanel();
        sourcePanel.setLayout( new GridLayout( 1, 1 ) );
        JLabel sourceLabel = new JLabel( "enter source text here:" );
        sourcePanel.add( sourceLabel );
        sourceText = new JTextArea();
        sourcePanel.add( sourceText );
        add( sourcePanel, BorderLayout.NORTH );

        //ActionListener buttonListener = new ActionListener();
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(3, 3));
        
        JButton but1 = new JButton("but1");
        but1.addActionListener(new buttonListener());
        buttonPanel.add(but1);
        JButton but2 = new JButton("but2");
        buttonPanel.add(but2);
        JButton but3 = new JButton("but3");
        buttonPanel.add(but3);
        JButton but4 = new JButton("but4");
        buttonPanel.add(but4);
        JButton but5 = new JButton("but5");
        buttonPanel.add(but5);
        JButton but6 = new JButton("but6");
        buttonPanel.add(but6);
        JButton but7 = new JButton("but7");
        buttonPanel.add(but7);
        JButton but8 = new JButton("but8");
        buttonPanel.add(but8);
        JButton but9 = new JButton("but9");
        buttonPanel.add(but9);

        add(buttonPanel, BorderLayout.CENTER);    




    //getContentPane( ).setBackground(Color.ORANGE);
        //setLayout(new BorderLayout( ));
        //JLabel aLabel = new JLabel("An applet a day keeps the doctor away.");
        //add(aLabel, BorderLayout.CENTER);    

        // Label to store messages
        // Main layout is a border layout
        // Messages go on top

        // Make a panel to store the game board buttons
        //. . .

        // Organized using a grid layout
        //. . .

        // Create game board
        //. . .

        gameOver = false;

        // Create buttons for each board and link each button back
        // to a coordinate
        for (int y=0; y<BOARDSIZE; y++)
        {
            for (int x=0; x<BOARDSIZE; x++)
            {
              // Initially no piece on each location
              // . . .

            }
        }

        //. . .                              // X goes first;
    }

    /**
    * @return char 'X' or 'Y' depending on  whoseturn it is.
    */
    public char getTurn()
    {
    return 'x';
        //. . .
    }

    /**
    * @param x The x coordinate of the board location we want to set
    * @param y The y coordinate of the board location we want to set
    * @param newValue the char to store at board[x][y]
    */
    public void setBoard(int x, int y, char newValue)
    {
        //. . .
    }

    /**
    * @return char The character (' ', 'X', or 'Y') stored at board[x][y]
    */
    public char getBoard(int x, int y)
    {
        return (board[x][y]);
    }

    /**
    * Notifies the game that a player moved, so the current player should be
    * toggled to the other player.
    */
    public void playerMoved()
    {
        //. . .
    }

    /**
    * Accessor if game over
    */
    public boolean gameIsOver()
    {
        return gameOver;
    }

    /**
    * Checks if a player won the game or if there was a draw.  In either
    * case the program exits after displaying a message.  If the game is
    * not over then the method exits.
    */
    public void checkGameOver()
    {
        boolean win;
        char first;

        // Check all rows across.  There is a winner if all entries are
        // the same character, but not ' '
        for (int y=0; y<BOARDSIZE; y++)
        {
          win = true;
          first = board[0][y];
          if (first != ' ')
          {
              for (int x=1; x<BOARDSIZE; x++)
              {
                  if (board[x][y]!=first) win=false;
              }
              if (win) {
                  messageLabel.setText(first + " is the winner!");
                  gameOver = true;
              }
          }
            }
        // Check all rows down. There is a winner if all entries are the same
        // character, but not ' '

        //. . .

        // Check diagonal top left to bottom right
        //. . .
        // Check diagonal bottom left to top right
        //. . .

        // Check if board is full.  If so, there is a draw.
        if (!gameOver)
            {
            int numpieces = 0;
            for (int x=0; x<BOARDSIZE; x++)
              for (int y=0; y<BOARDSIZE; y++)
              {
                //. . .
              }
            if (numpieces==BOARDSIZE*BOARDSIZE)
            {
                //. . .
            }
        }

    }
}


User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Action Listener Help
23 Mar, 2007 - 05:06 AM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
the class being private is not an issue, it is a good practise since it hides more code from the user, using this is a valid option, but i don't like it because it doesn't re-use code that could be called many times, instead i prefer the following:

1) create a private global variable of the class:
private ButtonListener blisten;

2) in your main method instantiate it:
blisten = new ButtonListener();

3) now you can add the listener:
but1.addactionlistener(blisten);

this ensures the same block of code in memory is being used on each call of this method, instead of creating a new instance each time with this.
User is offlineProfile CardPM
+Quote Post

spullen
RE: Action Listener Help
23 Mar, 2007 - 10:48 AM
Post #3

D.I.C Regular
Group Icon

Joined: 22 Mar, 2007
Posts: 330



Thanked: 1 times
Dream Kudos: 50
My Contributions
I don't know if this could be a problem, but when I make GUIs in Java I use
CODE
if(e.getSource() == someButton){/*Do Stuff*/}
.

Also, you don't need to import all of the classes if you do the star like this import java.awt.*;. So once you have that you don't need all of the other java.awt.<Class Name>;. You can do what you're doing but it saves keystrokes and makes the code look neater.

This post has been edited by spullen: 23 Mar, 2007 - 10:51 AM
User is offlineProfile CardPM
+Quote Post

Ryan747
RE: Action Listener Help
23 Mar, 2007 - 05:16 PM
Post #4

New D.I.C Head
*

Joined: 16 Oct, 2006
Posts: 26


My Contributions
I can see in your program that your using actionCommand I think this is the proper way of using it:

CODE

public void actionPerformed(ActionEvent e){
   if(e.getActionCommand().equals("but1")){
       //action
   }else if(e.getActionCommand().equals("but2")){
       //action
   }
}

User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Action Listener Help
23 Mar, 2007 - 05:49 PM
Post #5

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
that should be correct Ryan747, if this code is not placed inside a private class the this command will work just fine.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 05:20PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month