Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 3 of 4 FirstFirst 1234 LastLast
Results 51 to 75 of 86

Thread: Battleship GUI Program

  1. #51
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    for ( int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (  int j = 0; j < arrayOfButtons[i].length; j++)
                      arrayOfButtons[i][j] = new JButton("0");
                }
     
                for (int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (   int j = 0; j < arrayOfButtons[i].length; j++)
                      arrayOfButtons[i][j].addActionListener(this);
                }
     
     
                for ( int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (   int j = 0; j < arrayOfButtons[i].length; j++)
                      pane.add(arrayOfButtons[i][j]);
                }

    Perhaps it's these for loops. Is there any way I could make it into one?

  2. #52
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    I need to get it to figure out what button was clicked and get the indexes of those and set them to I and J.

    Then it'll work.

    But how do you do that?

  3. #53
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    How does your program set the values of i and j that you use for indexes?

    What does: e.getActionCommand().equals("0") have to do with the problem?

    What is the value of e.getActionCommand()? Use println() to display it!!! Then you'll know what the program is doing.

    You need to learn how to debug your program. Your assuming that your thoughts are somehow making into your code. Sometimes it works differently than you think. To see what it is doing, use System.out.println() to show values.
    I know what it's doing. i and j are initialized to 0, so it only works for 0, 0.

    How do I fix that problem? I've also noticed my battleship is moving.

  4. #54
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    How do I get it so it stops calling place Battleship every time I click a button?

  5. #55
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    It's only applying for 0,0 as that's what I initialized it to, but I have no idea how to get it to update according to which button I clicked nor do I know how to keep it from calling the method placeBattleship every time I hit a button, thus changing the location of the battleship. I know those are the only two sets of problems that are left. But I'm very tired right now and can't figure it out.

  6. #56
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by helloworld922 View Post
    umm... wow. Have you thought about using loops to create the buttons? That would drastically reduce the amount of code you have.

    for(int i = 0; i < 10; i++)
    {
         for (int j = 0; j < 10; j++)
         {
              // setup one button in here and store it into an array of buttons.
              buttons[i][j] = new Button(i + " " + j);
         }
    }
    Ok, nearly got it, but how do I get it from calling the method placeBattleship every time I hit a button, thus the battleship keeps moving.

    Also, how to I get it i and j to the right values:

      // Programmer: Paul Adcock          //
     // Project: GUI Project    //
     // Last Modification Date: 6/2/10 //
     /* The project makes an array of up to 100 buttons.  My
    	 if statements will keep asking user for a value between 2 and 10 till they do it.  Then I'm
    	 going to put the battleship in the array and then going to have actionEvent deal with if it's 
    	 not a hit and has a text of 0, I set them default to 0, then it changes the text of that button to an M.
    	 If they shoot there again one or more times, it changes it to an A.  If they actually hit the battleship, it changes the text to 
    	 an H, shows the number of shots, and then exits.  If they surrender, it asks them if they want to, and if they do, it shows the number of shots
    	 and then exits.  If they quit, it asks them if they want to, and if they do, it justs says a goodbye message and exits.  */
     
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
       import javax.swing.JFrame;
       import javax.swing.JDialog;
       import javax.swing.JPanel;
       import java.awt.Graphics;
       import javax.swing.ImageIcon;
       import java.util.*;
       import java.io.*;
       import java.awt.Component;
       import javax.swing.AbstractButton;
     
     
        public class BattleshipGUI extends JFrame 
        implements ActionListener
       { // beginning of class
        // label
          private JLabel shotsLabel, arraySize;
     
       // area where text is displayed and user would normally enter text but I have made it so the user can't alter the shot count.
          private JTextField shotsTF, arraySizeTF;
     
          JFrame frame;
     
          JButton [][] arrayOfButtons;
          char [][] charArray;
     
    	int x, y, i, j;
     
     
       // buttons
          private JButton surrenderB, quitB;
     
          private static final int WIDTH = 500;
          private static final int HEIGHT = 500;
     
     
           public BattleshipGUI()
          { // beginning of constructor
             setTitle("Battleship Game");
             Container pane = getContentPane();
     
     
                	// makes Label for shots
             shotsLabel = new JLabel("Shots: ",
                                      SwingConstants.RIGHT);
             arraySize= new JLabel("Array Size ",
                                      SwingConstants.RIGHT);	
     
            // makes Text Field for shots and makes the text field non-editable
             shotsTF = new JTextField(7);      
             shotsTF.setEditable(false);
     
             arraySizeTF = new JTextField(2);
             arraySizeTF.setEditable(false);
     
          			// makes the buttons and sets their value initially to 0 and makes the method actionPerformed
          			// a method of the class BattleshipGUI.  I don't need individual handlers.
     
             surrenderB = new JButton("Surrender");
             surrenderB.addActionListener(this);
     
             quitB = new JButton("Quit");
             quitB.addActionListener(this);
     
          // n is the size of the grid
             int n = 0;
             String gridSizeStr, outputStr;
             boolean isInRange = false;
          // while loop and boolean allow user to keep entering int values till n is between 2 and 10.  Also, it needs to have 
          // the array of buttons  in a square shape,  and also so I can place the battleship in the array and later use actionListeners to
          // change the text to either a M, an A, or a H.  Hence why all buttons in the array have the same label to begin with.
     
             shotsTF.setText("0");
             boolean isValid = false;
     
             while (isValid == false)
             { // beginning of while
                try
                { // beginning of try
                   gridSizeStr = JOptionPane.showInputDialog("Enter the size of the grid:");
                   n = Integer.parseInt(gridSizeStr);
     
                   if (n < 2)
                      throw new MyTooSmallException();
     
                   if (n > 10)
                      throw new MyTooBigException();
     
                   isValid = true;
     
                } // end of try
     
                    catch ( MyTooSmallException mtse)
                   { // beginning of catch
     
                      JOptionPane.showMessageDialog(null, "Enter a value that is not less than" 
                         + " 2 and is no greater than 10. " +"\n " + mtse.toString() );
     
                   } // end of catch
     
                    catch ( MyTooBigException mtbe)
                   { // beginning of catch
     
                      JOptionPane.showMessageDialog(null, "Enter a value that is not less than" 
                         + "2 and is no greater than 10. " +"\n " + mtbe.toString() );
     
                   } // end of catch
     
     
                    catch (NumberFormatException nfeRef)          
                   { // beginning of catch
                      JOptionPane.showMessageDialog(null,
                         "Enter an integer.  Exception "
                         + nfeRef.toString(),
                         "NumberFormatException",
                         JOptionPane.ERROR_MESSAGE);       
                   } // end of catch
     
             } // end of while 
     
     
             if (n >=2 && n <= 10)
             { // beginning of if				
     
     
     
                charArray = new char[n][n];
                for (  int x = 0; x < charArray.length; x++)
                {
                   for (  int y = 0; y < charArray[x].length; y++)
                      charArray[x][y] = '0'; 
     
                } 
     
                 arrayOfButtons = new JButton[n][n];
     
               for ( int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (  int j = 0; j < arrayOfButtons[i].length; j++)
                      arrayOfButtons[i][j] = new JButton("0");
                }
     
                for (int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (   int j = 0; j < arrayOfButtons[i].length; j++)
                      arrayOfButtons[i][j].addActionListener(this);
                }
     
     
                for ( int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (   int j = 0; j < arrayOfButtons[i].length; j++)
                      pane.add(arrayOfButtons[i][j]);
                } 
     
     
     
     
     
     
     
                pane.setLayout(new GridLayout((n+1), (n+1)));
     
     
                pane.add(surrenderB);
                pane.add(quitB);
                pane.add(shotsLabel);
                pane.add(shotsTF);
     
               // the char array is where the actual 1 square battleship is going to be placed.
               // it is a n by n grid and the other array needs to be too to make them parallel.  
               // A value in the arrayOfButtons[i][j] should be the same as charArray[x][y].
     
     
     
     
             } // end of if      
     
     
     
     
          // makes an n by n grid
     
     
             setSize(WIDTH, HEIGHT);
             setVisible(true);
             setDefaultCloseOperation(EXIT_ON_CLOSE);
     
     
          } // end of constructor
     
           public static void main(String[] args)
          { // beginning of main
             BattleshipGUI refVar = new BattleshipGUI();
     
     
     
          } // end of main
     
       	// this method handles the buttons.  
           public void actionPerformed(ActionEvent e)
          { // beginning of method
             String outputStr2, outputStr3, outputStr4, outputStr5, outputStr6;
             String outputStrM, outputStrA, outputStrAA;
             outputStrM = "Miss";
             outputStrA = "Already shot there";
             outputStrAA = "I told you that you already shot there";
     
             outputStr2 = "Are you sure you want to quit? ";
             outputStr3 = "You Quit.";
             outputStr4 = "Ok don't quit then." ;
             outputStr5 = "Thought not.";
             outputStr6 = "You surrendered.";
     
     
           int i, j, x,y;
             x = 0;
             i = 0;
             y = 0;
             j = 0;
     
    		/*	for (int r = 0; r < arrayOfButtons.length; r++)
    			{
    			for (int c = 0; c < arrayOfButtons[r].length; c++)
    			if (arrayOfButtons[r][c].isSelected())
    			{
    			i = r;
    			j = c;
    			}
    			} */
     
     
             int shots =  Integer.parseInt(shotsTF.getText());
     
             placeBattleship(charArray); 
     
             Integer tries;
             Integer tries2;
             Integer tries3;
             Integer tries4;
             Integer tries5;
     
             tries = shots;
             tries2 = shots;
             tries3 = shots;
             tries4 = shots;
             tries5 = shots;
     
             if (e.getActionCommand().equals("Quit"))
             { // beginning of if
                Object[] options = {"Yes",
                        "Continue Playing"};
     
                int n = JOptionPane.showOptionDialog(frame,
                   "Are you sure you want to Quit?",
                   "Quit",
                   JOptionPane.YES_NO_OPTION,
                   JOptionPane.QUESTION_MESSAGE,
                   null,        options,     options[0]); 
             // creates Yes and Continue playing butons buttons.
             		// if Yee button is clicked, sends output "You quit." as heading and sends a message "Adiós!" and exits when 
             		// user clicks OK on dialog box
                if (n == JOptionPane.YES_OPTION) 
                { // beginning of if
                   JOptionPane.showMessageDialog(null,"Adiós!", outputStr3,  JOptionPane.PLAIN_MESSAGE);
                   System.exit(0);
                } // end of if
                // changes the string the standard dialog box for the No button but still uses its predefined return value.  If user clicks on 
                // Continue Playing, sends title "Ok don't quit then." and the message "Whatever." and takes the user back to the grid.
                else if (n == JOptionPane.NO_OPTION)
                { // beginning of else if
                   JOptionPane.showMessageDialog(null,"Whatever.",  outputStr4,  JOptionPane.PLAIN_MESSAGE);
                } // end of else if
     
             } // end of if
     
             else if (e.getActionCommand().equals("Surrender"))
             { // beginning of else if
     
                Object[] options2 = {"Yes",
                        "No, I have not yet begun to fight!"};
                int p = JOptionPane.showOptionDialog(frame,
                   "Are you sure you want to Surrender?",
                   "Surrender?",
                   JOptionPane.YES_NO_OPTION,
                   JOptionPane.QUESTION_MESSAGE,
                   null,        options2,   options2[0]); 
             // creates Yes and No, I have not yet begun to fight! butons .
             		// if Yes button is clicked, sends output "You surrendered." as heading and sends a message "It took you [number of shots]
             		// shots!" and exits when user clicks OK on dialog box
                if (p == JOptionPane.YES_OPTION) 
                { // beginning of if
                // code for showing grid
                   arrayOfButtons[i][j].setText("B");
                   JOptionPane.showMessageDialog(null, "You took "  + shotsTF.getText() + " shots" , outputStr6, JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);
                } // end of if
                // changes the string the standard dialog box for the No button but still uses its predefined return value.  If user clicks on 
                // "No button", sends output "Thought not." and the title "You didn't surrender." and takes the user back to the grid.
                else if (p == JOptionPane.NO_OPTION)
                { // beginning of else if
                   JOptionPane.showMessageDialog(null, outputStr5, "You didn't surrender." , JOptionPane.PLAIN_MESSAGE);
                } // end of else if
             } // end of else if
     
     
             else if (e.getActionCommand().equals("0"))
             { // beginning of else if
     
     
                if (  Fire(charArray, x, y) == 'H')
                { // beginning of if
                   String outputStr7;
                   arrayOfButtons[i][j].setText("H");  // changes text on button to H
                   shots = shots + 1;
                   tries = new Integer(shots);
                   shotsTF.setText(tries.toString());
     
                   outputStr7 = "You sank my battleship. " + "\n" + "You sank my battleship in " + shotsTF.getText() + " tries";
                   JOptionPane.showMessageDialog(null, outputStr7 , "You win!", +  JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);
                }// end of if
     
                else 
                { // beginning of else
                   JOptionPane.showMessageDialog(null, outputStrM , "You missed!", +  JOptionPane.INFORMATION_MESSAGE);
                   arrayOfButtons[i][j].setText("M"); // changes text on button to M
                   shots = shots + 1;
                   tries2 = new Integer(shots);
                   shotsTF.setText(tries2.toString());
                   System.out.println(arrayOfButtons[i][j]);
                } // end of else
             } // end of else if 
                   // does this if text on button hit is M.
             else if (e.getActionCommand().equals("M"))
             { // beginning of else if
                shots = shots + 1;
                tries3 = new Integer(shots);
                shotsTF.setText(tries3.toString());
     
                JOptionPane.showMessageDialog(null, outputStrA , "Still a miss!", +  JOptionPane.INFORMATION_MESSAGE);
                arrayOfButtons[i][j].setText("A"); // changes text on button to A
             } // end of else if
                   // does this if text on button hit is A
             else if (e.getActionCommand().equals("A"))
             { // beginning of else if
                shots = shots + 1;
                tries4 = new Integer(shots);
                shotsTF.setText(tries4.toString());
     
                JOptionPane.showMessageDialog(null, outputStrAA , "Still a miss!", +  JOptionPane.INFORMATION_MESSAGE);
                arrayOfButtons[i][j].setText("A"); // changes text, sorta, on button to A
             } // end of else if
     
          } // end of method
     
          // the method placeBattleship, places the battleship by randomly choosing a
       // row and column coordinate and storing a 'B' there.  The 'B' is not displayed to 
       // the user unless the user hits the surrender button.  It takes the array as a parameter and 
       // should return nothing.  This method sets the location of the battleship.
     
           private static void placeBattleship(char charArray[][])
          { // beginning of method placeBattleship
             int valueOne, valueTwo;
             char B;
             valueOne= (int) ( 1 + (Math.random() * charArray.length -1)); 
             valueTwo = (int) ( 1 + (Math.random() * charArray.length -1 ));
             charArray[valueOne][valueTwo] = 'B';
     
     
          } //end of method placeBattleship
     
           public static char Fire(char charArray[][], int x, int y)
          { // beginning of method Fire
             char A;
             char M;
             char H;
     
             if (charArray[x][y] == 'B')  // if battleship is hit return H and end game
             { // beginning of if statement
                charArray[x][y] = 'H';
     
     
                return ('H');
     
             } // end of if statement
     
             else if (charArray[x][y] == 'M')  // this is else if 
                                              // because it could also 
                                              // be just a miss.
     
             { // beginning of else if statement
     
                charArray[x][y] = 'A';
     
                return ('A');
             } // end of else if statement
     
             else if (charArray[x][y] == 'A') // makes sure it won't set an A to an M again.
             { // beginning of else if  
     
                charArray[x][y] = 'A';
                return ('A');
             } // end of else if
             else
     
             { // beginning of else statement
                charArray[x][y] = 'M'; 
                return ('M');                                          
             } // end of else statement
          } // end of method fire
     
     
       } // end of program

  7. #57
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    Yes, you should move the assignment statements into one set of loops instead of 3.

    To determine what button was clicked, you need to store some data with the button that has its x,y location.
    Two ways: Look at the put/getClientProperties() methods
    Extend the JButton class with a class that saves the location of the button and has a get() method to retrieve it.
    In your listener use the Event.getSource() method to get a reference to the JButton object.

    .. in the create buttons loop
    Point loc = new Point(j, i); // save col and row
    arrayBtn[i][j].putClientProperties("loc", loc);  // save location with button
    ...
    // in listener
    JButton jb = (JButton)evt.getSource();
    Point loc = (Point)jb.getClientProperties("loc");  // retrieve buttons location
    ...


    how do I get it from calling the method placeBattleship every time I hit a button
    Talk to the programmer that's writing the code and have him move the call to a better location.
    Last edited by Norm; June 4th, 2010 at 07:49 PM.

  8. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 4th, 2010)

  9. #58
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Yes, you should move the assignment statements into one set of loops instead of 3.

    To determine what button was clicked, you need to store some data with the button that has its x,y location.
    Two ways: Look at the put/getClientProperties() methods
    Extend the JButton class with a class that saves the location of the button and has a get() method to retrieve it.
    In your listener use the Event.getSource() method to get a reference to the JButton object.

    .. in the create buttons loop
    Point loc = new Point(j, i); // save col and row
    arrayBtn[i][j].putClientProperties("loc", loc);  // save location with button
    ...
    // in listener
    JButton jb = (JButton)evt.getSource();
    Point loc = (Point)jb.getClientProperties("loc");  // retrieve buttons location
    ...



    Talk to the programmer that's writing the code and have him move the call to a better location.
    Well, it'll keep calling placeBattleship every time because GUIs are usually executed more than one till some condition is met.

    Is there a way to store the coordinates and set them to that so that it'll always be the same no matter how many times it executes?

    Calling it in main won't work. Calling it in the constructor never places the battleship. Calling it in the actionPerformed causes it to move. Where should the programmer put it?

  10. #59
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Yes, you should move the assignment statements into one set of loops instead of 3.

    To determine what button was clicked, you need to store some data with the button that has its x,y location.
    Two ways: Look at the put/getClientProperties() methods
    Extend the JButton class with a class that saves the location of the button and has a get() method to retrieve it.
    In your listener use the Event.getSource() method to get a reference to the JButton object.

    .. in the create buttons loop
    Point loc = new Point(j, i); // save col and row
    arrayBtn[i][j].putClientProperties("loc", loc);  // save location with button
    ...
    // in listener
    JButton jb = (JButton)evt.getSource();
    Point loc = (Point)jb.getClientProperties("loc");  // retrieve buttons location
    ...



    Talk to the programmer that's writing the code and have him move the call to a better location.
    JButton jb = (JButton)evt.getSource();

    That doesn't compile.

    I've spent a month on this stupid project but I can't give up now. I wish I could get the Battleship to stay put. Where do I call placeBattleship() where it won't be called every time I hit a button?

    I've got an idea.

    Is it possible to get a text from a text field even if it's not added to the pane, but if it exits?

    If so, then I'll make an x and y TF.

    I'll set their text to the value for the battleship and then, in place battleship,
    I'll get it to keep using those values.

    Get a times counter and when times = 2, alter how the coordinates are set:

    And get the values to the x and y value.
    Last edited by javapenguin; June 4th, 2010 at 09:36 PM.

  11. #60
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    JButton jb = (JButton)evt.getSource();

    That doesn't compile.
    Please post the error messages.

    Where do I call placeBattleship() where it won't be called every time I hit a button?
    Where do you call placeBattleship()? Is it in the listener that is called every time you hit a button?
    Move it somewhere else.

    Calling it in the constructor never places the battleship
    Add println() statements to your code to show where the battleship is and every place where its location can be changed like when charArray's contents are changed.

  12. #61
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Please post the error messages.


    Where do you call placeBattleship()? Is it in the listener that is called every time you hit a button?
    Move it somewhere else.


    Add println() statements to your code to show where the battleship is and every place where its location can be changed like when charArray's contents are changed.
    I have an idea how to do with the moving battleship, even if I have to put it in the listener.

    I can't put it sooner or it won't put it at all.

    I haven't tried before the constructor but that probably won't work.

    I'm hoping I can use a get text on a text field that exists but was never added to the pane, so the user can't see the coordinates, to store them in so that the first time it'll place it and add up a variable called times2 which'll change the text field times to 1 so that it'll do a different way of placing the batlteship by getting the two coordinates it give the first time from the text field and always reusing them thereafter. I hope this'll work.

    Also, it was getProperty, not getProperties.

    It doesn't like this:

    /* JButton jb = (JButton) evt.getSource());

  13. #62
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    It doesn't like this:
    What happens?

  14. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

  15. #63
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    What happens?
    It doesn't compile. It's syntax.

    Also, battleship still moving. Where should I call it?

    In the listener?

    In the constructor, where it'll never execute?

    Somewhere else?

  16. #64
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Ok, now the battleship is staying put, but I can never seem to hit it.

    So it keeps setting it to 0,0.

    I think it's now set so that you can only hit the battleship if you hit it in your first try.

    What's going on?

    Oh, it's resetting the tf but not the variables I'm getting to the tf. At least not right away, which isn't good.
    Last edited by javapenguin; June 5th, 2010 at 04:29 PM.

  17. #65
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    What's going on?
    Sounds like you need to debug your system.

    Add lots and lots of: System.out.println("var1= " + var1 + ", var2=" + var2);
    to your code. Change var1, var2 etc as appropriate.

  18. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

  19. #66
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Sounds like you need to debug your system.

    Add lots and lots of: System.out.println("var1= " + var1 + ", var2=" + var2);
    to your code. Change var1, var2 etc as appropriate.

    Ok, the battleship has now, I think, weighed anchor, but it appears to still not be changing after button is pushed. Maybe it's not supposed to. Oh, wait....

      public void actionPerformed(ActionEvent e)
          { // beginning of method
             String outputStr2, outputStr3, outputStr4, outputStr5, outputStr6;
             String outputStrM, outputStrA, outputStrAA;
             outputStrM = "Miss";
             outputStrA = "Already shot there";
             outputStrAA = "I told you that you already shot there";
     
             outputStr2 = "Are you sure you want to quit? ";
             outputStr3 = "You Quit.";
             outputStr4 = "Ok don't quit then." ;
             outputStr5 = "Thought not.";
             outputStr6 = "You surrendered.";
     
     
    				int times2 = Integer.parseInt(times.getText());
     
    				System.out.println("xTF: " + xTF.getText());
    				System.out.println("yTF: " + yTF.getText());
     
    				int a = Integer.parseInt(xTF.getText());
    				int b = Integer.parseInt(yTF.getText());
     
    				System.out.println("a: " + a);
    				System.out.println("b: " + b);
          		placeBattleship(charArray, times2, a, b); 
     
     
     
     
           int i, j, x,y;
             x = 0;
             i = 0;
             y = 0;
             j = 0;
     
    		/*	for (int r = 0; r < arrayOfButtons.length; r++)
    			{
    			for (int c = 0; c < arrayOfButtons[r].length; c++)
    			if (arrayOfButtons[r][c].isSelected())
    			{
    			i = r;
    			j = c;
    			}
    			} */
     
     
             int shots =  Integer.parseInt(shotsTF.getText());
     
     
     
     
    			/*	JButton jb = (JButton + evt.getSource());
     
    Point loc = (Point)jb.getClientProperty("loc");  // retrieve buttons location */
     
     
     
     
             Integer tries;
             Integer tries2;
             Integer tries3;
             Integer tries4;
             Integer tries5;
     
             tries = shots;
             tries2 = shots;
             tries3 = shots;
             tries4 = shots;
             tries5 = shots;
     
             if (e.getActionCommand().equals("Quit"))
             { // beginning of if
                Object[] options = {"Yes",
                        "Continue Playing"};
     
                int n = JOptionPane.showOptionDialog(frame,
                   "Are you sure you want to Quit?",
                   "Quit",
                   JOptionPane.YES_NO_OPTION,
                   JOptionPane.QUESTION_MESSAGE,
                   null,        options,     options[0]); 
             // creates Yes and Continue playing butons buttons.
             		// if Yee button is clicked, sends output "You quit." as heading and sends a message "Adiós!" and exits when 
             		// user clicks OK on dialog box
                if (n == JOptionPane.YES_OPTION) 
                { // beginning of if
                   JOptionPane.showMessageDialog(null,"Adiós!", outputStr3,  JOptionPane.PLAIN_MESSAGE);
                   System.exit(0);
                } // end of if
                // changes the string the standard dialog box for the No button but still uses its predefined return value.  If user clicks on 
                // Continue Playing, sends title "Ok don't quit then." and the message "Whatever." and takes the user back to the grid.
                else if (n == JOptionPane.NO_OPTION)
                { // beginning of else if
                   JOptionPane.showMessageDialog(null,"Whatever.",  outputStr4,  JOptionPane.PLAIN_MESSAGE);
                } // end of else if
     
             } // end of if
     
             else if (e.getActionCommand().equals("Surrender"))
             { // beginning of else if
     
                Object[] options2 = {"Yes",
                        "No, I have not yet begun to fight!"};
                int p = JOptionPane.showOptionDialog(frame,
                   "Are you sure you want to Surrender?",
                   "Surrender?",
                   JOptionPane.YES_NO_OPTION,
                   JOptionPane.QUESTION_MESSAGE,
                   null,        options2,   options2[0]); 
             // creates Yes and No, I have not yet begun to fight! butons .
             		// if Yes button is clicked, sends output "You surrendered." as heading and sends a message "It took you [number of shots]
             		// shots!" and exits when user clicks OK on dialog box
                if (p == JOptionPane.YES_OPTION) 
                { // beginning of if
                // code for showing grid
                   arrayOfButtons[i][j].setText("B");
                   JOptionPane.showMessageDialog(null, "You took "  + shotsTF.getText() + " shots" , outputStr6, JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);
                } // end of if
                // changes the string the standard dialog box for the No button but still uses its predefined return value.  If user clicks on 
                // "No button", sends output "Thought not." and the title "You didn't surrender." and takes the user back to the grid.
                else if (p == JOptionPane.NO_OPTION)
                { // beginning of else if
                   JOptionPane.showMessageDialog(null, outputStr5, "You didn't surrender." , JOptionPane.PLAIN_MESSAGE);
                } // end of else if
             } // end of else if
     
     
             else if (e.getActionCommand().equals("0"))
             { // beginning of else if
     
     
                if (  Fire(charArray, x, y) == 'H')
                { // beginning of if
                   String outputStr7;
                   arrayOfButtons[i][j].setText("H");  // changes text on button to H
                   shots = shots + 1;
                   tries = new Integer(shots);
                   shotsTF.setText(tries.toString());
     
                   outputStr7 = "You sank my battleship. " + "\n" + "You sank my battleship in " + shotsTF.getText() + " tries";
                   JOptionPane.showMessageDialog(null, outputStr7 , "You win!", +  JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);
                }// end of if
     
                else 
                { // beginning of else
                   JOptionPane.showMessageDialog(null, outputStrM , "You missed!", +  JOptionPane.INFORMATION_MESSAGE);
                   arrayOfButtons[i][j].setText("M"); // changes text on button to M
                   shots = shots + 1;
                   tries2 = new Integer(shots);
                   shotsTF.setText(tries2.toString());
                   System.out.println(arrayOfButtons[i][j]);
                } // end of else
             } // end of else if 
                   // does this if text on button hit is M.
             else if (e.getActionCommand().equals("M"))
             { // beginning of else if
                shots = shots + 1;
                tries3 = new Integer(shots);
                shotsTF.setText(tries3.toString());
     
                JOptionPane.showMessageDialog(null, outputStrA , "Still a miss!", +  JOptionPane.INFORMATION_MESSAGE);
                arrayOfButtons[i][j].setText("A"); // changes text on button to A
             } // end of else if
                   // does this if text on button hit is A
             else if (e.getActionCommand().equals("A"))
             { // beginning of else if
                shots = shots + 1;
                tries4 = new Integer(shots);
                shotsTF.setText(tries4.toString());
     
                JOptionPane.showMessageDialog(null, outputStrAA , "Still a miss!", +  JOptionPane.INFORMATION_MESSAGE);
                arrayOfButtons[i][j].setText("A"); // changes text, sorta, on button to A
             } // end of else if
     
     
          } // end of method
     
          // the method placeBattleship, places the battleship by randomly choosing a
       // row and column coordinate and storing a 'B' there.  The 'B' is not displayed to 
       // the user unless the user hits the surrender button.  It takes the array as a parameter and 
       // should return nothing.  This method sets the location of the battleship.
     
           private  void placeBattleship(char charArray[][], int times2, int a, int b)
          { // beginning of method placeBattleship
             int valueOne, valueTwo;
             char B;
    			if (times2 == 0)
    			{
             valueOne= (int) ( 1 + (Math.random() * charArray.length -1)); 
             valueTwo = (int) ( 1 + (Math.random() * charArray.length -1 ));
             charArray[valueOne][valueTwo] = 'B';
     
     
    			   	Integer stupidInt;
     
    				stupidInt = valueOne;
     
    				Integer stupidInt2;
     
    				stupidInt2 = valueTwo;
    				times2 = times2 + 1;
     
    				Integer storeDatVariable;
     
    				storeDatVariable = times2;
     
    				times.setText(storeDatVariable.toString());
     
    					xTF.setText(stupidInt.toString());
    				    yTF.setText(stupidInt2.toString());
    				}
     
     
    				else
    				charArray[a][b] = 'B';
    				System.out.println("xTF: " + xTF.getText());
    				System.out.println("yTF: " + yTF.getText());
    				System.out.println("a: " + a);
    				System.out.println("b: " + b);
     
     
     
     
     
     
     
          } //end of method placeBattleship

    After first button:


    xTF: 0
    yTF: 0
    a: 0
    b: 0
    xTF: 0
    yTF: 1
    a: 0
    b: 0


    after second button(also, any button, including quit and surrender, will count as a button, but if all works out, that shouldn't make any difference anyway.)

    xTF: 0
    yTF: 1
    a: 0
    b: 1
    xTF: 0
    yTF: 1
    a: 0
    b: 1

    Should be after first time:

    xTF: 0
    yTF: 0
    a: 0
    b: 0
    xTF: 0
    yTF: 1
    a: 0
    b: 1


    Also, code

    tton jb = (JButton) evt.getSource());

    doesn't work as evt hasn't been defined.

    So what class is it from anyway? EventObject?

    if I have it say size 2, the only one where it's kinda likely I'll hit it in the first try, and hit it the first time, it says
    xTF: 0
    yTF: 0
    a: 0
    b: 0
    xTF: 0
    yTF: 0
    a: 0
    b: 0

    And of course, after that the game is over.

    Because of the other glitch, 0,0 seems to have become a no boating zone and at times a boat safety zone.
    Last edited by javapenguin; June 5th, 2010 at 05:28 PM.

  20. #67
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    Yes, evt represents the Event object reference passed to the listener. I didn't look thru your code for correct spelling.
    That object is the one the user clicked on. It could contain its x,y location on the nxn grid if you code it.

  21. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

  22. #68
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    I never used event object before. I only suspected that as I looked up that method online and it came up in java api as coming from that class, though some classes can have the same method names, though that'll be a problem if they are in an "is a" relationship.

    Ok, so what do I call the event object,

    i.e.

    Event object evt;

    How do I put something in evt?

  23. #69
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    Look at post #57

  24. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

  25. #70
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Look at post #57
    Ok, what kind of Object goes in the constructor?

    EventoObject evt = new EventObject();

    BattleshipGUI.java:305: cannot find symbol
    symbol : constructor EventObject()
    location: class java.util.EventObject
    EventObject evt = new EventObject();
    ^
    Also, just out of curiosity, what happens theoretically if you pass a method of parameter that gets its value changed in that method? Ok, no that's not what I meant. I meant, if it was first defined in that method, was used as a parameter in another method, and was then sent back to that method again to be altered once more. Would it throw some kind of exception or be confused?

    Never mind about that last part for now, how do I fix the error.
    Last edited by javapenguin; June 5th, 2010 at 06:44 PM.

  26. #71
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Look at post #57
    I did.

    What goes in the constructor?

    EventObject evt = new EventObject();

    I tried
    Object obj; = new Object();
    EventObject evt  = new EventObj(ob);

    but it threw a ClassCastException.

    Could I try

    Object obj.

    Point loc;

    And I already have
    Point loc = new point (i,j); // in constructor

    obj = loc;
    Last edited by javapenguin; June 5th, 2010 at 07:34 PM.

  27. #72
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    You don't create an event object. The system passes one to the listener.

  28. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

  29. #73
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    You don't create an event object. The system passes one to the listener.
    I don't?

    So I use the actionEvent variable?

  30. #74
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    You don't create an event object. The system passes one to the listener.
    No, it passes an actionEvent to the listener.

    Wait, which is a subclass of EventObject.
    Last edited by javapenguin; June 5th, 2010 at 08:09 PM.

  31. #75
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,552
    Thanks
    45
    Thanked 1,953 Times in 1,927 Posts

    Default Re: Battleship GUI Program

    Better read up on listeners and the event objects that are passed to them.

  32. The Following User Says Thank You to Norm For This Useful Post:

    javapenguin (June 5th, 2010)

Page 3 of 4 FirstFirst 1234 LastLast