Page 3 of 3 FirstFirst 123
Results 41 to 60 of 60
  1. #41
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Your problem is that you have one ActionListener for everything, and so the whole shebang will be called if a button is pressed or if a menu is activated. You have some code in there outside of if blocks that always get called (the error message will tell you where this is), that you don't want to get called if the action was initiated by a menu press. Again, this is easy to see if the code is properly indented since then you know what is in if blocks and what isn't.

    A short term solution is to put that code into an if block so it is only called if a button has been pressed. A better solution is to use separate ActionListeners for very separate actions. I prefer to use anonymous inner listeners for this.

  2. #42
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Something kind of like this??

    Java Code:
    JButton b1 = new JButton("About");
    b1.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
    
    		if (arg.equals ("About")){
    		String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
    		JOptionPane.showMessageDialog(null,message,
    		"About TicTacToe", JOptionPane.INFORMATION_MESSAGE);
    
    
     	  }
    
        }

  3. #43
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    I think you meant:

    Java Code:
    JButton b1 = new JButton("About");
    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            [color=red]String arg = e.getActionCommand();[/color]
            if(arg.equals ("About")) {
                String message = 
                        "Ryan's TicTacToe \nStructured Programming"
                        + "\nCopyright 2011\nAll rights reserved";
                JOptionPane.showMessageDialog(
                        null, message, "About TicTacToe", 
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    [color=red]});[/color]

    If you think about it for a minute you do not need to check what the action command is - because you are attaching the action listener to a button whose text you already know.

    So

    Java Code:
    JButton b1 = new JButton("About");
    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message = 
                    "Ryan's TicTacToe \nStructured Programming"
                    + "\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(
                    null,message, "About TicTacToe", 
                    JOptionPane.INFORMATION_MESSAGE);
        }
    });

    Something kind of like this?

    To find out you have to try it: see what you see, then understand what you see.
    Last edited by pbrockway2; 04-03-2011 at 02:35 AM.

  4. #44
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Well i added this but as of now im still getting nothing when i click the "exit button" i appreciate it very much for you helping me this far im glad you can help me.

    Java Code:
     public void actionPerformed(ActionEvent e) {
        count++;
    
     if(count % 2 == 0){
          letter = "O";
          } else {
          letter = "X";
    
    }
    
    
    String arg = e.getActionCommand();{
        if (arg.equals ("Exit")){
            System.exit(0);
    
            if (arg == ("Clear")){
    
        }
      }
    }
    
    
    
    JButton b1 = new JButton("About");
    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(
                    null,message, "About TicTacToe",
                    JOptionPane.INFORMATION_MESSAGE);
    
          }
    
    });
    
    
    /*Write the letter to the button and deactivate it*/
        JButton pressedButton = (JButton)e.getSource();
           pressedButton.setText(letter);
              pressedButton.setEnabled(false);
                pressedButton.setBackground(Color.RED);
    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
     /*Determine who won*/
         for(int i=0; i<=7; i++){
            if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
               buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                  buttons[winCombinations[i][0]].getText() != ""){
                   win = true;
    
               }
          }
     }
    
    
        public static void main(String[] args){
            TicTacToe5 starter = new TicTacToe5();
    
    
      }
    }
    Last edited by Ryan10; 04-03-2011 at 03:11 AM.

  5. #45
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Sorry, but I can't read that.

    It doesn't look like it would compile - but I could be missing somerthing as the indents and brace placement is making your code very obscure.

  6. #46
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    There i edited my last post is that a little better?

  7. #47
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Im not even getting a dialog box do you guys think it has to do with that?

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

    Default

    You'll want to give your variables names that make sense, that make your code self-commenting. So I'd change JButton "b1" to aboutButton. Are you sure that you add this button to your GUI? Consider creating and posting an SSCCE

  9. #49
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Im not sure where i would add this "aboutButton" since i didnt need a button for the Exit command

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import java.awt.Color;
    
    
    
    public class TicTacToe5 extends Frame implements ActionListener {
        /*Instance Variables*/
        private int[][] winCombinations = new int[][] {
                {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
                {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
                {0, 4, 8}, {2, 4, 6}             //diagonal wins
    
            };
        private JFrame window = new JFrame("Tic-Tac-Toe");
        private JButton buttons[] = new JButton[9];
        private int count, xWins, oWins, X, O, SOUTH, b1;
        private String letter = "";
        private boolean win = false;
        private TextField lcd;
        private Choice colors= new Choice();
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    
        public TicTacToe5(){
    
    		JMenuBar menuBar = new JMenuBar();
    		window.setJMenuBar(menuBar);
    
    		JMenu fileMenu = new JMenu("File",true);
    		menuBar.add(fileMenu);
    
    		JMenu mnuAbout = new JMenu("About", true);
    		menuBar.add(mnuAbout);
    
    /////////////////////////////////////////////////////////////////////////////
    
        //////////////About Menu///////////
    
    
    
    	JMenuItem aboutAction = new JMenuItem("About TicTacToe");
    	mnuAbout.add(aboutAction);
    	aboutAction.addActionListener(this);
    	aboutAction.setActionCommand("About");
    
    
    //////*Creates the Exit Meny bar*//////
    	JMenuItem exitAction = new JMenuItem("Exit");
    	fileMenu.add(exitAction);
    	exitAction.addActionListener(this);
    	exitAction.setActionCommand("Exit");
    
    
    
    
        lcd = new TextField(10);
    	lcd.setEditable(false);
        add(lcd, BorderLayout.SOUTH);
    
    ////////////////////////////////////////////////////////////////////////////////////////////
    
    	/*Create Window*/
    
        window.setSize(300,300);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new GridLayout(3,3));
    
    	/*Add Buttons To The Window*/
        for(int i=0; i<=8; i++){
    
            buttons[i] = new JButton();
                window.add(buttons[i]);
                   buttons[i].addActionListener(this);
    }
    
        /*Make The Window Visible*/
            window.setVisible(true);
    
    }
    
    
    ///////////////////////////////////////////////////////////
    
    
        public void actionPerformed(ActionEvent e) {
            count++;
    
            /*Calculate whose turn it is*/
            if(count % 2 == 0){
    			letter = "O";
            } else {
                letter = "X";
    }
    
    
    
    		    String arg = e.getActionCommand();{
    		if (arg.equals ("Exit")){
    		    System.exit(0);
    
    
    
    
            if (arg.equals ("Clear")){
    
        }
      }
    }
    
    
    JButton aboutButton = new JButton("About");
    aboutButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(
                    null,message, "About TicTacToe",
                    JOptionPane.INFORMATION_MESSAGE);
    			}
    
    });
    
    
            /*Write the letter to the button and deactivate it*/
             JButton pressedButton = (JButton)e.getSource();
             pressedButton.setText(letter);
             pressedButton.setEnabled(false);
             pressedButton.setBackground(Color.RED);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
            /*Determine who won*/
            for(int i=0; i<=7; i++){
                if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
                    buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                    	buttons[winCombinations[i][0]].getText() != ""){
                    	win = true;
    
                  }
    		  }
               }
    
    
    
        public static void main(String[] args){
            TicTacToe5 starter = new TicTacToe5();
    
    
      }
    }

    Here is another code that i am "going by for help" and all of the menu functions works correct maybe this will help our problem


    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JOptionPane;
    
    public class TTT extends Frame implements ActionListener
    {
    private Button keys[];
    private Panel keypad;
    private TextField lcd;
    private boolean first;
    private boolean foundKey;
    private boolean clearText;
    
    ////////////MENU//////////////////////////////////////////////////////////
    public TTT()
    {
    MenuBar mnuBar = new MenuBar();
    setMenuBar(mnuBar);
    
    Menu mnuFile = new Menu("File", true);
    mnuBar.add(mnuFile);
    MenuItem mnuFileExit = new MenuItem("Exit");
    mnuFile.add(mnuFileExit);
    
    Menu mnuEdit = new Menu("Edit", true);
    mnuBar.add(mnuEdit);
    MenuItem mnuEditClear = new MenuItem("Clear");
    mnuEdit.add(mnuEditClear);
    
    Menu mnuAbout = new Menu("About", true);
    mnuBar.add(mnuAbout);
    MenuItem mnuAboutTicTacToe = new MenuItem("About TicTacToe");
    mnuAbout.add(mnuAboutTicTacToe);
    
    mnuFileExit.addActionListener(this);
    mnuEditClear.addActionListener(this);
    mnuAboutTicTacToe.addActionListener(this);
    
    mnuFileExit.setActionCommand("Exit");
    mnuEditClear.setActionCommand("Clear");
    mnuAboutTicTacToe.setActionCommand("About");
    
    lcd = new TextField(10);
    lcd.setEditable(false);
    keypad = new Panel();
    keys = new Button [10];
    first = true;
    clearText = true;
    
    for (int i=0; i<=9; i++)
    keys[i] = new Button();
    
    //////////////LAYOUT BORDER////////////////////////////////////////////
    
    setLayout(new BorderLayout());
    keypad.setLayout(new GridLayout(3,3,10,10));
    
    for (int i=1; i<=9; i++)
    keypad.add(keys[i]);
    
    add(lcd, BorderLayout.SOUTH);
    add(keypad, BorderLayout.CENTER);
    
    addWindowListener(
    new WindowAdapter()
    {
    ////////////////EXIT,ABOUT,CLEAR////////////////////////////////////////
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    }
    );
    }
    
    public void actionPerformed(ActionEvent e)
    {
    
    String arg = e.getActionCommand();
    if (arg == "Exit")
    System.exit(0);
    
    if (arg == "Clear")
    {
    
    }
    
    
    if (arg == "About")
    {
    String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
    JOptionPane.showMessageDialog(null,message,
    "About TicTacToe", JOptionPane.INFORMATION_MESSAGE);
    }
    }
    /////////////////TITLE,IMAGE,HEIGHT,WIDTH/////////////////////////////////////////////
    public static void main(String args[])
    
    {
    TTT f = new TTT();
    f.setTitle("TicTacToe Game");
    f.setBounds(200,200,300,300);
    f.setVisible(true);
    
    Image icon = Toolkit.getDefaultToolkit().getImage("Image.gif");
    f.setIconImage(icon);
    
    }
    }
    Last edited by Ryan10; 04-03-2011 at 03:51 AM.

  10. #50
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    no ideas everyone stopped talking

  11. #51
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default

    I have added some comments to your code, as I said before you have made a mess in your actionPerformed method. Please go through your code and read the comments..


    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import java.awt.Color;
    
    
    
    public class TicTacToe5 extends Frame implements ActionListener { // by extending Frame your app becomes Frame, 
    // for later use I suggest use of JFrame instead Frame
        /*Instance Variables*/
        private int[][] winCombinations = new int[][] {
                {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
                {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
                {0, 4, 8}, {2, 4, 6}             //diagonal wins
    
            };
        private JFrame window = new JFrame("Tic-Tac-Toe"); // since your app extends Frame (JFrame) you don't need to create another JFrame here
        private JButton buttons[] = new JButton[9];
        private int count, xWins, oWins, X, O, SOUTH, b1;
        private String letter = "";
        private boolean win = false;
        private TextField lcd;
        private Choice colors= new Choice();
    
    
    /////////////////////////////////////////////////////////////////////////////////////////
    
        public TicTacToe5(){
    
    		JMenuBar menuBar = new JMenuBar();
    		window.setJMenuBar(menuBar); // instead use: setJMenuBar(menuBar)
    
    		JMenu fileMenu = new JMenu("File",true);
    		menuBar.add(fileMenu);
    
    		JMenu mnuAbout = new JMenu("About", true);
    		menuBar.add(mnuAbout);
    
    /////////////////////////////////////////////////////////////////////////////
    
        //////////////About Menu///////////
    
    
    
    	JMenuItem aboutAction = new JMenuItem("About TicTacToe");
    	mnuAbout.add(aboutAction);
    	aboutAction.addActionListener(this);
    	aboutAction.setActionCommand("About");
    
    
    //////*Creates the Exit Meny bar*//////
    	JMenuItem exitAction = new JMenuItem("Exit");
    	fileMenu.add(exitAction);
    	exitAction.addActionListener(this);
    	exitAction.setActionCommand("Exit");
    
    
    
    
        lcd = new TextField(10); // don't know what this is
    	lcd.setEditable(false);
        add(lcd, BorderLayout.SOUTH);
    
    ////////////////////////////////////////////////////////////////////////////////////////////
    
    	/*Create Window*/
    
        window.setSize(300,300);  // again, no need for 'window' just use: setSize(300, 300);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // like above
        window.setLayout(new GridLayout(3,3)); // like above
    
    	/*Add Buttons To The Window*/
        for(int i=0; i<=8; i++){
    
            buttons[i] = new JButton();
                window.add(buttons[i]); // just: add(buttons[i];
                   buttons[i].addActionListener(this);
    }
    
        /*Make The Window Visible*/
            window.setVisible(true); // just: setVisible(true)
    
    }
    
    
    ///////////////////////////////////////////////////////////
    
    
        public void actionPerformed(ActionEvent e) { 
            count++;
    
            /*Calculate whose turn it is*/
            if(count % 2 == 0){
    			letter = "O";
            } else {
                letter = "X";
    		}
    		
    		String arg = e.getActionCommand();{ // what is this '{' for?
    		
    		if (arg.equals ("Exit")){
    		    System.exit(0);
    
    
    		// here you need to finish above if statement with '}'
    
            if (arg.equals ("Clear")){ // this part of code is never reached since it is after System.exit(0);
    		// also if you use if statement to test some condition then you should continue with 'else if{}'
    		// in that way when first condition is reached system will not waste time by going through other if statements
        } // one of these is probably sufficient I didn't try it
      }
    }
    
    
    JButton aboutButton = new JButton("About");  // why this button when you already have JMenuItem("About TicTacToe");
    aboutButton.addActionListener(new ActionListener() { // all this code is not necessary, you didn't even add this button to frame
        public void actionPerformed(ActionEvent e) { // this also, this part of code is already in actionPerformed()
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(
                    null,message, "About TicTacToe",
                    JOptionPane.INFORMATION_MESSAGE);
    			}
    
    });
    
    
            /*Write the letter to the button and deactivate it*/
             JButton pressedButton = (JButton)e.getSource(); // here you will always get an ClassCastException when actionListener is trigered with MenuItem and not JButton
             pressedButton.setText(letter);  // to avoid this put this part of code in try-catch 
             pressedButton.setEnabled(false);
             pressedButton.setBackground(Color.RED);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
            /*Determine who won*/
            for(int i=0; i<=7; i++){
                if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
                    buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                    	buttons[winCombinations[i][0]].getText() != ""){
                    	win = true;
    
                  }
    		  }
               }
    
    
    
        public static void main(String[] args){
            TicTacToe5 starter = new TicTacToe5();
    
    
      }
    }

    I have rewrited your code in actionPerformed following your design, just change your code with this one

    Java Code:
    public void actionPerformed(ActionEvent e) {
        count++;
    
        /*Calculate whose turn it is*/
        if(count % 2 == 0){
            letter = "O";
        } else {
            letter = "X";
        }
    		
        String arg = e.getActionCommand();
    
        if (arg.equals("Exit")){
            System.exit(0);
        }
        else if (arg.equals("About")){
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(null,message,"About TicTacToe", JOptionPane.INFORMATION_MESSAGE);	
        }
    
            /*Write the letter to the button and deactivate it*/
        try{
            JButton pressedButton = (JButton)a.getSource();
            pressedButton.setText(letter);
            pressedButton.setEnabled(false);
            pressedButton.setBackground(Color.RED);
        }
        catch(Exception exc){
        }
    
        for(int i=0; i<=7; i++){
            if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
                buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                buttons[winCombinations[i][0]].getText() != ""){
                    win = true;
             }
        }
    }
    Last edited by milovan; 04-03-2011 at 10:04 PM.

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

    Default

    Quote Originally Posted by milovan View Post
    I have rewrited your code in actionPerformed following your design, just change your code with this one

    Java Code:
    public void actionPerformed(ActionEvent e) {
        count++;
    
        /*Calculate whose turn it is*/
        if(count % 2 == 0){
            letter = "O";
        } else {
            letter = "X";
        }
    		
        String arg = e.getActionCommand();
    
        if (arg.equals("Exit")){
            System.exit(0);
        }
        else if (arg.equals("About")){
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(null,message,"About TicTacToe", JOptionPane.INFORMATION_MESSAGE);	
        }
    
            /*Write the letter to the button and deactivate it*/
        try{
            JButton pressedButton = (JButton)a.getSource();
            pressedButton.setText(letter);
            pressedButton.setEnabled(false);
            pressedButton.setBackground(Color.RED);
        }
        catch(Exception exc){
        }
    }
    This will increment count and try to write a letter to a JButton even if the about button is pressed. This is another reason for keeping the tic-tac-toe button ActionListener and other button listeners separate.

    Also, we probably shouldn't be encouraging newbies to ignore exceptions:

    Java Code:
        catch(Exception exc){
        }
    Last edited by Fubarable; 04-03-2011 at 10:13 PM.

  13. #53
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default

    This will increment count and try to write a letter to a JButton even if the about button is pressed. This is another reason for keeping the tic-tac-toe button ActionListener and other button listeners separate.
    You are right about this. As I said, I was following his idea, so he could understand where he was wrong, didn't said it is good aprroach.
    of course we can get around this by decreasing count:
    Java Code:
    else if (arg.equals("About")){
            String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
            JOptionPane.showMessageDialog(null,message,"About TicTacToe", JOptionPane.INFORMATION_MESSAGE);	
        [B]count--;[/B]
    }

    And yet, as you said this is not good aprroach, but for begining it will work, giving him a chance to understand his mistakes and to learn more.

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

    Default

    Quote Originally Posted by milovan View Post
    You are right about this. As I said, I was following his idea, so he could understand where he was wrong, didn't said it is good aprroach.
    of course we can get around this by decreasing count:

    That's using a kludge to fix a bad design. Better to fix the design in the first place.


    And yet, as you said this is not good aprroach, but for begining it will work, giving him a chance to understand his mistakes and to learn more.

    Better he learn to keep separate actions separate. For example (and I know that there's no way that he can hand this code in):

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class SimpleTicTacToe extends JPanel {
       private static final int BUTTON_FONT_POINTS = 64;
       private static final Font TTT_BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, BUTTON_FONT_POINTS);
       private static final String[] XO = {"X", "O"};
       private JButton[][] tttButtons = new JButton[3][3];
       private int buttonCount = 0;
    
       public SimpleTicTacToe() {
          TttButtonListener tttBtnListener = new TttButtonListener();
    
          JPanel tttPanel = new JPanel(new GridLayout(3, 3, 5, 5));
          for (int row = 0; row < tttButtons.length; row++) {
             for (int col = 0; col < tttButtons[row].length; col++) {
                JButton btn = new JButton("   ");
                btn.setFont(TTT_BTN_FONT);
                btn.addActionListener(tttBtnListener); // add listener to ttt button
                tttPanel.add(btn);
                tttButtons[row][col] = btn;
             }
          }
    
          // all other non tictactoe buttons use anonymous inner classes
          JButton resetButton = new JButton("Reset");
          resetButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                resetActionPerformed();
             }
          });
    
          JButton aboutButton = new JButton("About");
          aboutButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                aboutActionPerformed();
             }
          });
    
          JButton exitButton = new JButton("Exit");
          exitButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                Window win = SwingUtilities.getWindowAncestor(SimpleTicTacToe.this);
                win.dispose();
             }
          });
    
          JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
          buttonPanel.add(resetButton);
          buttonPanel.add(aboutButton);
          buttonPanel.add(exitButton);
    
          setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
          setLayout(new BorderLayout(5, 5));
          add(tttPanel, BorderLayout.CENTER);
          add(buttonPanel, BorderLayout.SOUTH);
       }
    
       private void resetActionPerformed() {
          buttonCount = 0;
          for (JButton[] buttonRow : tttButtons) {
             for (JButton button : buttonRow) {
                button.setText("");
             }
          }
       }
    
       private void aboutActionPerformed() {
          // TODO: show about action
       }
    
       public void checkForWin() {
          // TODO: complete this method
    
       }
    
       // private listener class, only for the tictactoe buttons
       private class TttButtonListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             JButton button = (JButton) e.getSource();
             if (button.getText().trim().isEmpty()) {
                button.setText(XO[buttonCount]);
                buttonCount++;
                buttonCount %= 2;
    
                checkForWin();
             }
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Simple TicTacToe");
          frame.getContentPane().add(new SimpleTicTacToe());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  15. #55
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    so i tried putting in the code you supposedly fixed and it doesnt work..im confused as to where i should go from here now.

  16. #56
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Fubarable i got the about action to work in your code that you created but am confused as to what to do for the "check to win part"

  17. #57
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    I dont even know if this could even work i just came up with something maybe i can get some help to make it work. Thanks

    Java Code:
    private int[][] winCombinations = new int[][] {
                   {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
                   {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
                   {0, 4, 8}, {2, 4, 6}   //diagonal wins
    
    		   };

    Java Code:
       private void aboutActionPerformed() {
          // TODO: show about action
    
          String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
               JOptionPane.showMessageDialog(null,message,"About TicTacToe", JOptionPane.INFORMATION_MESSAGE);
    
       }
    
       public void checkForWin() {
          // TODO: complete this method
    
          for(int i=0; i<=7; i++){
    	              if( ??[winCombinations[i][0]].getText().equals(??[winCombinations[i][1]].getText()) &&
    	                  ??[winCombinations[i][1]].getText().equals(??[winCombinations[i][2]].getText()) &&
    	                  ??[winCombinations[i][0]].getText() != ""){
                    win = true;
    
    			}
    		}
    
    
    }

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

    Default

    My code was not for copying and pasting as it most definitely will not work in your program. Rather it was just an example of how to separate out the listeners for the tic tac toe buttons vs other buttons or menus by using a private inner class for the former and anonymous inner classes for the latter.

  19. #59
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    works for me

  20. #60
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    guess im going to leave this forum with no solution....awesome haha

Page 3 of 3 FirstFirst 123

Similar Threads

  1. TicTacToe game
    By pinotje in forum New To Java
    Replies: 9
    Last Post: 12-23-2010, 06:49 PM
  2. Tictactoe game
    By Fowler in forum New To Java
    Replies: 11
    Last Post: 10-31-2010, 10:55 PM
  3. I need feedback on my TicTacToe game
    By kiregad in forum New To Java
    Replies: 4
    Last Post: 03-21-2010, 11:09 PM
  4. Need help with a menu button in a game
    By pjr5043 in forum Java Applets
    Replies: 1
    Last Post: 12-07-2008, 10:30 PM
  5. TicTacToe Game
    By Ebtihal in forum New To Java
    Replies: 0
    Last Post: 01-09-2008, 12:01 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
  •