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 4 of 4 FirstFirst ... 234
Results 76 to 86 of 86

Thread: Battleship GUI Program

  1. #76
    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
    Better read up on listeners and the event objects that are passed to them.
    Ok, the compiler errors went away, but it still is only changing 0,0.

    What do I do with it now?

    Oh, so loc shows which button was clicked.

    Also, shouldn't I have to Point classes?

    How do I get the x and the y if I have just one?

    What if I had loc be i and loc2 be j.

    Then I'd have

    if (arrayOfButtons[loc[[loc2] == charCharacter)....

    Also, could I make two more Point classes, these would store the i and j of the battleship?

    Could I make them in the listener, and then pass them to the placeBattleship, and get it to set it to those the second time of letting it choose a new spot?

    If so, everything could work!
    Last edited by javapenguin; June 5th, 2010 at 08:24 PM.

  2. #77
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Battleship GUI Program

    I have no idea how you've gotten this far.
    I can't begin to explain what you need to know.

    Good luck.

  3. #78
    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 got the location thing to work.

    Now I'm going to try to get the battleship to stay in one spot and not get lost.

  4. #79
    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
    I have no idea how you've gotten this far.
    I can't begin to explain what you need to know.

    Good luck.
    Part of the code you suggested has made my buttons Quit and Surrender not work as your Point loc thing made them part of it to, but they aren't part of the array.

    I'm very tired right now.

    Also, I've never had to fiddle with Point and all those classes before. I'm only at a 1012 level.

    I don't know how the teacher ever expected us to get it done.

    The program was due May 10th, it's now June 5th and I still haven't given up on it.

    I was able to figure out the button thing on my own as it worked, but somehow made my two non-array buttons part of that too, and I don't want that.


  5. #80
    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

     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;
       import java.awt.Event;
       import java.awt.Point;
       import java.util.EventObject;
     
     
        public class BattleshipGUI extends JFrame 
        implements ActionListener
       { // beginning of class
        // label
          private JLabel shotsLabel, arraySize, iCoordinate, jCoordinate, xCord, yCord;
     
       // 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, xTF, yTF, times, iCoordinateTF, jCoordinateTF, xCordTF, yCordTF;
     
          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);	
             iCoordinate = new JLabel("X value ",
                                      SwingConstants.RIGHT);	
             jCoordinate = new JLabel("Y value ",
                                       SwingConstants.RIGHT);
             xCord = new JLabel("X value ",
                                      SwingConstants.RIGHT);	
             yCord = new JLabel("Y value ",
                                       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);
     
             xTF = new JTextField(2);
             xTF.setEditable(false);
     
             yTF = new JTextField(2);
             yTF.setEditable(false);
     
             times = new JTextField(5);
             times.setEditable(false);
     
             iCoordinateTF = new JTextField(2);
             iCoordinateTF.setEditable(false);
     
             jCoordinateTF = new JTextField(2);
             jCoordinateTF.setEditable(false);
     
             xCordTF = new JTextField(2);
             xCordTF.setEditable(false);
     
             yCordTF = new JTextField(2);
             yCordTF.setEditable(false);
     
             times.setText("0");
     
             xTF.setText("0");
             yTF.setText("0");
             iCoordinateTF.setText("0");
             jCoordinateTF.setText("0");
     
             xCordTF.setText("0");
             yCordTF.setText("0");
     
     
          			// 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]);
                }  */
     
                for (int i = 0; i < arrayOfButtons.length; i++)
                {
                   for (int j = 0; j < arrayOfButtons[i].length; j++)
                   {
                      arrayOfButtons[i][j] = new JButton("0");
                      arrayOfButtons[i][j].addActionListener(this);
                      pane.add(arrayOfButtons[i][j]);
                      Point loc = new Point(i, j); // save col and row
                      arrayOfButtons[i][j].putClientProperty("loc", loc);  // save location with button
     
     
                   }
     
                }
     
     
     
     
     
     
     
                pane.setLayout(new GridLayout((n+1), (n+1)));
     
     
                pane.add(surrenderB);
                pane.add(quitB);
                pane.add(shotsLabel);
                pane.add(shotsTF);
             	pane.add(times);
    				/*
             	pane.add(iCoordinate);
             	pane.add(iCoordinateTF);
             	pane.add(jCoordinate);
             	pane.add(jCoordinateTF); */
     
               // 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 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);
     
    			 int iVar4 = Integer.parseInt(xCordTF.getText());
     
    			 int jVar4 = Integer.parseInt(yCordTF.getText());
     
    			 System.out.println(iVar4 + "," + jVar4);
     
             placeBattleship(charArray, times2, a, b, iVar4, jVar4); 
     
     
     
     
             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) e.getSource();
     
             Point loc = (Point)jb.getClientProperty("loc");  // retrieve buttons location 
     
             double t = loc.getX();
             Double variable1;
     
             variable1 = t;
     
             int 	iVar = variable1.intValue();
     
             Integer anotherVariable;
     
             anotherVariable = iVar;
     
             iCoordinateTF.setText(anotherVariable.toString());
     
             int iVar2 = Integer.parseInt(iCoordinateTF.getText());
             double u = loc.getY();
     
             Double variable2;
     
             variable2 = u;
     
             int jVar = variable2.intValue();
     
             Integer anotherVariable2;
     
             anotherVariable2 = jVar;
     
             jCoordinateTF.setText(anotherVariable2.toString());
     
             int jVar2 = Integer.parseInt(jCoordinateTF.getText());
     
     
     
             jCoordinateTF.setText(variable2.toString());
     
          //   int iVar = Integer.parseInt(iCoordinateTF.getText());
     
          //	int jVar = Integer.parseInt(jCoordinateTF.getText());
     
     
     
     
             System.out.println(loc.getLocation());
     
             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[iVar2][jVar2].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[iVar2][jVar2].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[iVar2][jVar2].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[iVar2][jVar2].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[iVar2][jVar2].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, int iVar4, int jVar4)
          { // 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';
     
                Point battleshipLoc = new Point(valueOne,valueTwo);
     
     
                double penguin = battleshipLoc.getX();
                Double variable3;
     
                variable3= penguin;
     
                int 	iVar3 = variable3.intValue();
     
                Integer anotherVariable3;
     
                anotherVariable3 = iVar3;
     
                xCordTF.setText(anotherVariable3.toString());
     
    				double wenguin = battleshipLoc.getY();
     
    				Double variable4;
     
    				variable4 = wenguin;
     
    				int jVar3 = variable4.intValue();
     
    				Integer anotherVariable4;
     
    				anotherVariable4 = jVar3;
     
    				yCordTF.setText(anotherVariable4.toString());
     
     
     
     
     
                Integer stupidInt;
     
                stupidInt = valueOne;
     
                Integer stupidInt2;
     
                stupidInt2 = valueTwo;
               //  times2 = times2 + 1;
     
                Integer storeDatVariable;
     
    				times2 = times2 + 1;
     
                storeDatVariable = times2;
     
                times.setText(storeDatVariable.toString());
     
                xTF.setText(stupidInt.toString());
                yTF.setText(stupidInt2.toString());
             }
     
     
             else
                charArray[iVar4][jVar4] = '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

  6. #81
    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

    Well, I almost got it to work. The battleship at last is anchored. The setTexts work in the correct spots, but, as I used the same reference variable as I did for the getActionCommand() calls, it tried to assign points to my two non-array buttons and of course they don't have any point so it's throwing a Null Pointer Exception when I hit those two buttons. Should I try and add them as special parts to the array? What should I do to fix this final problem?

  7. #82
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Battleship GUI Program

    I used the same reference variable as I did for the getActionCommand() calls, it tried to assign points to my two non-array buttons
    Use a different listener for those buttons.
    Or in your actionPerformed() method use the Event getSource() method to get pointer to the button pressed and compare it against the pointers to those two buttons and react accordingly.

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

    javapenguin (June 6th, 2010)

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

    Smile Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    Use a different listener for those buttons.
    Or in your actionPerformed() method use the Event getSource() method to get pointer to the button pressed and compare it against the pointers to those two buttons and react accordingly.
    Actually, what I'm going to try and do is create handlers for those two other buttons. That way they won't get null values that screw it up. Then the game will work.

  10. #84
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Battleship GUI Program

    create handlers for those two other buttons
    What's a handler vs a listener?

  11. #85
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Battleship GUI Program

    Quote Originally Posted by Norm View Post
    What's a handler vs a listener?
    I guess a handler is what a listener calls to perform the action required. Usually the handler is a method in the listener (e.g. actionPerformed).

  12. #86
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Battleship GUI Program

    Thanks. Makes sense.

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

    javapenguin (November 30th, 2010)

Page 4 of 4 FirstFirst ... 234