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.

Results 1 to 18 of 18

Thread: Trying to create a battleship game but am having ActionListener issues due to scoping

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

    Default Trying to create a battleship game but am having ActionListener issues due to scoping

    I've finally figured that it might be better to have the class implement ActionListener so that way I can, slightly, lessen the impact of nested ActionListeners.

     
     
       import java.util.*;
       import javax.swing.*;
       import java.awt.event.*;
       import java.awt.*;
       import java.io.*;
     
       public class TwoDBattleshipGame implements ActionListener
       {
          private JSplitPane compPane, humPane;
          final private JPanel topCompPanel;
          final private JPanel bottomCompPanel;
          final private JPanel topHumPanel;
          final private JPanel bottomHumPanel;
          private HumanPlayer p1, p2;
          private ComputerPlayer cp;
          private JButton[][] humanGrid;
          private JButton[][] humanGrid2;
          private JButton[][] computerGrid;
          private int i, j;
     
     
          protected class Player
          {
             private int x;
             private int y;
             private int opposingX;
             private int opposingY;
             private String name;
     
     
     
             public Player(String name)
             {
     
                setName(name);
     
             }
     
             public Player()
             {
                setName("John Doe");
     
             }
     
             public void setX(int x)
             {
                this.x = x;
             }
     
             public int getX()
             {
                return x;
             }
     
             public void setY(int y)
             {
                this.y = y;
             }
     
             public int getY()
             {
                return y;
             }
     
             public void setOpposingX(int opposingX)
             {
                this.opposingX = opposingX;
     
             }
     
             public int getOpposingX()
             {
                return opposingX;
             }
     
             public void setOpposingY(int opposingY)
             {
                this.opposingY = opposingY;
             }
     
             public int getOpposingY()
             {
                return opposingY;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
     
     
     
          }
     
          private class HumanPlayer extends Player
          {
             private char[][] grid;
             private int size;
     
             public HumanPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
     
             }
     
             private void setGridSize(int size)
             {
                this.size = size;
             }
     
             private int getGridSize()
             {
                return size;
             }
     
     
     
             public HumanPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
             }
     
             public void placeBattleship(int x, int y)
             {
                setX(x);
                setY(y);
     
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
             public char fire(int x, int y)
             {
                if (grid[x][y] == grid[getOpposingX()][getOpposingY()])
                   return 'H';
                else
                {
                   if ((grid[x][y] != grid[getOpposingX()][getOpposingY()]) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      return 'M';
     
                   }
                   else if (grid[x][y] == 'M')
                   {
                      grid[x][y] = 'A';
                      return 'A';
     
                   }
     
                   else
                      return 'A';
     
                }
     
     
             }
     
     
     
          }
     
          private class ComputerPlayer extends Player
          {
     
             private char[][] grid;
             private int size;
     
             public ComputerPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public ComputerPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public void setGridSize(int size)
             {
                this.size = size;
             }
     
             public int getGridSize()
             {
                return size;
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
     
             public char fire(int x, int y)
             {
                if (grid[x][y] == grid[getOpposingX()][getOpposingY()])
                   return 'H';
                else
                {
                   if ((grid[x][y] != grid[getOpposingX()][getOpposingY()]) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      return 'M';
     
                   }
                   else if (grid[x][y] == 'M')
                   {
                      grid[x][y] = 'A';
                      return 'A';
     
                   }
     
                   else
                      return 'A';
     
                }
     
     
     
             }
             public void placeBattleship()
             {
     
                int x = (int) (Math.random() * grid.length);
                int y = (int) (Math.random() * grid.length);
     
                setX(x);
                setY(y);
     
             }
          }
     
          public TwoDBattleshipGame()
          {
             JFrame contentHuman = new JFrame("Human Player");
     
             final JDialog jf = new JDialog();
             jf.setTitle("Select an option.");
             jf.setVisible(true);
             ButtonGroup bg = new ButtonGroup();
             JRadioButton option1 = new JRadioButton("Human vs. Computer");
             JRadioButton option2 = new JRadioButton("Human vs. Human");
             bg.add(option1);
             bg.add(option2);
             jf.add(option1);
             jf.add(option2);
             jf.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
             JDialog.setDefaultLookAndFeelDecorated(true);
             jf.add(option1);
             jf.add(option2);
             jf.setLayout(new GridLayout(2,1));
             jf.setMinimumSize(new Dimension(200,200));
             jf.setResizable(false);
             jf.setBackground(Color.GREEN);
             topHumPanel = new JPanel();
             topCompPanel = new JPanel();
             bottomCompPanel = new JPanel();
             bottomHumPanel = new JPanel();
             humPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topHumPanel, bottomHumPanel);
             humPane.setVisible(true);
             contentHuman.setContentPane(humPane);
             contentHuman.setVisible(true);
             contentHuman.setMinimumSize(new Dimension(300,300));
             option1.addActionListener(this);
     
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                         jf.setVisible(false);
                         int gs = Integer.parseInt(JOptionPane.showInputDialog ("Enter grid size.", "Enter grid size."));
                         humanGrid = new JButton[gs][gs];
                         System.out.println(humanGrid);
     
                         for ( int i =0; i < humanGrid.length; i++)
                         {
                            for ( int j = 0; j < humanGrid[i].length; j++)
                            {
                               humanGrid[i][j] = new JButton("?");
                               topHumPanel.add(humanGrid[i][j]);
                               setHumanP1I(i);
                               setHumanP1J(j);
                               humanGrid[i][j].addActionListener(this);
     
                                     new ActionListener() {
                                        public void actionPerformed(ActionEvent e)
                                        {
     
                                           if (p1.fire(getHumanP1I(),getHumanP1J()) == 'H')
                                              JOptionPane.showMessageDialog(null, "You sunk my battleship!");
                                           else if (p1.fire(getHumanP1I(), getHumanP1J()) == 'M')
                                           {
                                              JOptionPane.showMessageDialog(null,"Miss");
                                              humanGrid[getHumanP1I()][getHumanP1J()].setText("M");
     
                                           }
     
                                           else if (p1.fire(getHumanP1I(),getHumanP1J()) == 'A' && humanGrid[getHumanP1I()][getHumanP1J()].getText().equals("M"))
                                           {
                                              JOptionPane.showMessageDialog(null, "Already shot there.");
                                              humanGrid[getHumanP1I()][getHumanP1J()].setText("A");
     
     
                                           }
     
                                           else
                                           {
                                              JOptionPane.showMessageDialog(null, "Already shot there.");
     
                                           }
                                        }});
                            }
                         }
     
                         topHumPanel.setLayout(new GridLayout(gs,gs));
     
     
                         String name = JOptionPane.showInputDialog("Enter name of player.", "Enter name of player.");
                         p1 = new HumanPlayer(name, gs);
                         String cpName = JOptionPane.showInputDialog("Enter name of computer player.", "Enter name of computer player.");
                         cp = new ComputerPlayer(cpName, gs);
     
                         int xLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter x location of battleship."));
                         int yLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter y location of battleship."));
                         p1.placeBattleship(xLoc,yLoc);
                         cp.setOpposingX(xLoc);
                         cp.setOpposingY(yLoc);
                         cp.placeBattleship();
                      }});
     
             option2.addActionListener(
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                      }});
     
     
     
     
          }
     
          public void setHumanP1I(int i)
          {
             this.i = i;
          }
     
          public int getHumanP1I()
          {
             return i;
          }
     
          public void setHumanP1J(int j)
          {
             this.j = j;
          }
     
          public int getHumanP1J()
          {
             return j;
          }
     
          public static void main(String[] args)
          {
     
             JOptionPane.showMessageDialog(null, "Welcome to Battleship Game.", "Welcome", JOptionPane.INFORMATION_MESSAGE);
             new TwoDBattleshipGame();
     
          }
     
          public void actionPerformed(ActionEvent e)
          {
     
     
          }
       }

    How do I get the ActionListeners so that nothing will go out of scope and all the objects can communicate with each other?

    I know, or have an idea, of how to deal with the being able to have a computer player and yet stop it from making 1000000 moves before the human player can even blink. I've got an idea to disable the buttons but I'm more concerned about the scoping issue right now. I keep being told that I have to make several variables final, including ints sometimes, so I decided to change it all to go in the class's ActionListener instead of having nested ActionListeners. However, I'm still confused on how I can handle it with the scoping so things don't always have to be final, even when it's very bad for them to be final.

    I'm in the process of changing the ActionListeners to go over to the class ActionListener, instead of, as it previously was, being nested ActionListeners.

    I know I can use a bunch of nested

    if(e.getActionCommand().equals().....) but still am a bit confused on how to keep everything in the proper scope.

    That setHumanP1I was made because of a scoping issue I was having.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    do I get the ActionListeners so that nothing will go out of scope
    Make the action listeners inner classes and make the "nothing" class variables.

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

    javapenguin (December 19th, 2011)

  4. #3
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    How will one of the ActionListeners be able to access stuff from an inner ActionListener class?

    Basically the buttons on the first window having ActionListeners that cause a bunch of new ActionListeners to be available, but only if that button is clicked, hence I'm trying to figure out how to avoid the nesting of the "inner" ActionListeners that go with the Battleship Grid inside of the JSplitPane thing.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    How will one of the ActionListeners be able to access stuff from an inner ActionListener class
    Write a small test program with inner classes and see if the inner class can access outer class level variables and methods.

  6. #5
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    The problem wasn't just mere scope, it was to figure out which button I'm hitting. An e.getActionCommand() or even an e.getSource() shouldn't tell me the x and y loc of the button that is hit. The inner classes will make the scoping better but still won't deal with that problem.

    That's why I was going with the nested listeners.

    I did just have one rather silly idea of how to deal with that problem, but should I go this route or is there another (simpler) way?

    I had thought of simply extending the JButton class and having a thing that will show the button as usual, but also will keep track of some X and Y int values, which will happen to correspond to the values in the 2D array.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    figure out which button I'm hitting.
    The getSource method will return a reference to the button that was the source of the event.
    You can use the JComponent class's ClientProperties to save data with any Swing component, like a custom class that holds data about the component like its x,y location.

  8. #7
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    No idea what ClientProperties does but how can getSource() in an ActionListener be sure that an object is indeed a JButton so it doesn't perform a getX() on something that's not an instance of my new JButton subclass (SpeicalJButton)?

    will this work:

    Object obj = e.getSource();

    if (obj instanceof SpecialJButton)
    {

    }

    .......

    Also, I was referring to the x and y value of it's position in the JButton array, not x,y location on the screen.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    No idea what ClientProperties does
    You wouldn't unless you read the API doc. Did you do that and use Find for clientproperty?

  10. #9
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    Do you mean

    putClientProperty(Object key, Object value)
    ?

    Anyway, I've already made the SpecialJButton class. It will compile now but now it's running into a weird instance of a IndexOutOfBounds or something and it's somehow in the 300's despite there not being that many values even if you multiplied the x by the y dimension of the array.

     
     
       import java.util.*;
       import javax.swing.*;
       import java.awt.event.*;
       import java.awt.*;
       import java.io.*;
     
       public class TwoDBattleshipGame implements ActionListener
       {
          private JSplitPane compPane, humPane;
          final private JPanel topCompPanel;
          final private JPanel bottomCompPanel;
          final private JPanel topHumPanel;
          final private JPanel bottomHumPanel;
          private HumanPlayer p1, p2;
          private ComputerPlayer cp;
          private SpecialJButton[][] humanGrid;
          private SpecialJButton[][] humanGrid2;
          private SpecialJButton[][] computerGrid;
          private int i, j;
          private JFrame contentHuman;
          private JDialog jf;
     
          public class SecondListenerClass implements ActionListener {
             public void actionPerformed(ActionEvent e)
             {
                SpecialJButton sjb = (SpecialJButton) e.getSource();
     
                if (p1.fire(sjb.getX(),sjb.getY()) == 'H')
                {
     
                   JOptionPane.showMessageDialog(null, "You sunk my battleship!");
     
                }
                else if (p1.fire(sjb.getX(), sjb.getY()) == 'M')
                {
                   JOptionPane.showMessageDialog(null,"Miss");
                   humanGrid[sjb.getX()][sjb.getY()].setText("M");
     
                }
     
                else if (p1.fire(sjb.getX(),sjb.getY()) == 'A' && humanGrid[sjb.getX()][sjb.getY()].getText().equals("M"))
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
                   humanGrid[sjb.getX()][sjb.getY()].setText("A");
     
     
                }
     
                else
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
     
                }
     
             }
          }
     
          public class SpecialJButton extends JButton
          {
     
             private int xLoc;
             private int yLoc;
     
             public SpecialJButton(String text, String toolTip, int xLoc, int yLoc, Color c)
             {
                super(text);
                setToolTipText(toolTip);
                setXLoc(xLoc);
                setYLoc(yLoc);
                setBackground(c);
     
             }
     
             public void setXLoc(int xLoc)
             {
                this.xLoc = xLoc;
             }
     
             public int getXLoc()
             {
                return xLoc;
             }
     
             public void setYLoc(int yLoc)
             {
                this.yLoc = yLoc;
             }
     
             public int getYLoc()
             {
                return yLoc;
             }
     
          }
     
          public class FirstListenerClass implements ActionListener {
     
             private SecondListenerClass slc;
             public FirstListenerClass()
             {
                slc = new SecondListenerClass();
     
             }
             public void actionPerformed(ActionEvent e)
             {
     
                jf.setVisible(false);
                int gs = Integer.parseInt(JOptionPane.showInputDialog ("Enter grid size.", "Enter grid size."));
                humanGrid = new SpecialJButton[gs][gs];
                System.out.println(humanGrid);
                topHumPanel.setLayout(new GridLayout(gs,gs));
     
     
                String name = JOptionPane.showInputDialog("Enter name of player.", "Enter name of player.");
                p1 = new HumanPlayer(name, gs);
                String cpName = JOptionPane.showInputDialog("Enter name of computer player.", "Enter name of computer player.");
                cp = new ComputerPlayer(cpName, gs);
     
                int xLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter x location of battleship."));
                int yLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter y location of battleship."));
                p1.placeBattleship(xLoc,yLoc);
                cp.setOpposingX(xLoc);
                cp.setOpposingY(yLoc);
                cp.placeBattleship();
     
     
                for ( int i =0; i < humanGrid.length; i++)
                {
                   for ( int j = 0; j < humanGrid[i].length; j++)
                   {
                      humanGrid[i][j] = new SpecialJButton("?", "("+i+","+j+")", i, j, Color.BLUE);
                      topHumPanel.add(humanGrid[i][j]);
                      humanGrid[i][j].addActionListener(slc);
                   }
                }
             }
          }
     
     
          protected class Player
          {
             private int x;
             private int y;
             private int opposingX;
             private int opposingY;
             private String name;
             private Integer shots;
             protected char[][] grid;
     
     
             public Player(String name)
             {
     
                setName(name);
                shots = 0;
     
             }
     
             public Player()
             {
                setName("John Doe");
                shots = 0;
             }
     
             public void setShots(Integer shots)
             {
                this.shots = shots;
             }
     
             public Integer getShots()
             {
                return shots;
             }
     
             public void setX(int x)
             {
                this.x = x;
             }
     
             public int getX()
             {
                return x;
             }
     
             public void setY(int y)
             {
                this.y = y;
             }
     
             public int getY()
             {
                return y;
             }
     
             public void setOpposingX(int opposingX)
             {
                this.opposingX = opposingX;
     
             }
     
             public int getOpposingX()
             {
                return opposingX;
             }
     
             public void setOpposingY(int opposingY)
             {
                this.opposingY = opposingY;
             }
     
             public int getOpposingY()
             {
                return opposingY;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
             public char fire(int x, int y)
             {
                if (grid[x][y] == grid[getOpposingX()][getOpposingY()])
                {  
                   setShots(getShots() + 1);
                   return 'H';
                }
                else
                {
                   if ((grid[x][y] != grid[getOpposingX()][getOpposingY()]) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      setShots(getShots() + 1);
                      return 'M';
     
                   }
                   else if (grid[x][y] == 'M')
                   {
                      grid[x][y] = 'A';
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                   else
                   {
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                }
             }
     
          }
     
          private class HumanPlayer extends Player
          {
     
             private int size;
     
             public HumanPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
     
             }
     
             private void setGridSize(int size)
             {
                this.size = size;
             }
     
             private int getGridSize()
             {
                return size;
             }
     
     
     
             public HumanPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
             }
     
             public void placeBattleship(int x, int y)
             {
                setX(x);
                setY(y);
     
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
     
          }
     
          private class ComputerPlayer extends Player
          {
     
             private int size;
     
             public ComputerPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public ComputerPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public void setGridSize(int size)
             {
                this.size = size;
             }
     
             public int getGridSize()
             {
                return size;
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
             public void placeBattleship()
             {
     
                int x = (int) (Math.random() * grid.length);
                int y = (int) (Math.random() * grid.length);
     
                setX(x);
                setY(y);
     
             }
          }
     
          public TwoDBattleshipGame()
          {
             contentHuman = new JFrame("Human Player");
             FirstListenerClass flc = new FirstListenerClass();
             jf = new JDialog();
             jf.setTitle("Select an option.");
             jf.setVisible(true);
             ButtonGroup bg = new ButtonGroup();
             JRadioButton option1 = new JRadioButton("Human vs. Computer");
             JRadioButton option2 = new JRadioButton("Human vs. Human");
             bg.add(option1);
             bg.add(option2);
             jf.add(option1);
             jf.add(option2);
             jf.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
             JDialog.setDefaultLookAndFeelDecorated(true);
             jf.add(option1);
             jf.add(option2);
             jf.setLayout(new GridLayout(2,1));
             jf.setMinimumSize(new Dimension(200,200));
             jf.setResizable(false);
             jf.setBackground(Color.GREEN);
             topHumPanel = new JPanel();
             topCompPanel = new JPanel();
             bottomCompPanel = new JPanel();
             bottomHumPanel = new JPanel();
             humPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topHumPanel, bottomHumPanel);
             humPane.setVisible(true);
             contentHuman.setContentPane(humPane);
             contentHuman.setVisible(true);
             contentHuman.setMinimumSize(new Dimension(300,300));
             option1.addActionListener(flc);
     
     
     
     
     
     
     
             option2.addActionListener(
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                      }});
     
     
     
     
          }
     
          public void setHumanP1I(int i)
          {
             this.i = i;
          }
     
          public int getHumanP1I()
          {
             return i;
          }
     
          public void setHumanP1J(int j)
          {
             this.j = j;
          }
     
          public int getHumanP1J()
          {
             return j;
          }
     
          public static void main(String[] args)
          {
     
             JOptionPane.showMessageDialog(null, "Welcome to Battleship Game.", "Welcome", JOptionPane.INFORMATION_MESSAGE);
             new TwoDBattleshipGame();
     
          }
     
          public void actionPerformed(ActionEvent e)
          {
     
     
          }
       }


     

    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 319
    at TwoDBattleshipGame$Player.fire(TwoDBattleshipGame. java:230)
    at TwoDBattleshipGame$SecondListenerClass.actionPerfo rmed(TwoDBattleshipGame.java:30)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEven tMulticaster.java:272)
    at java.awt.Component.processMouseEvent(Component.jav a:6288)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:605 3)
    at java.awt.Container.processEvent(Container.java:204 1)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4651)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:643)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:602)
    at java.awt.EventQueue$1.run(EventQueue.java:600)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:616)
    at java.awt.EventQueue$2.run(EventQueue.java:614)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 613)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)





    It's indicating this part as the reason it threw the exception.

    if (grid[x][y] == grid[getOpposingX()][getOpposingY()])

    Somehow I think I'm telling it to either sink my own battleship (i.e. getting the getX() and getOpposingX() and getY() and getOpposingY() mixed up) or I'm not setting the opposing grid size and it's going out of bounds, though why it'd go so very out of bounds like in the 300's is beyond me.
    Last edited by javapenguin; December 20th, 2011 at 09:31 PM.

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    yes that is it.

  12. #11
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    Quote Originally Posted by Java API
    The clientProperty dictionary is not intended to support large scale extensions to JComponent nor should be it considered an alternative to subclassing when designing a new component.
    Also, what would I set the for the value anyway? How would I access these properties. Seems now I'd have to fiddle with Maps or HashTables.

    I think I've got an idea though of what you meant. Let's see if that'll work. Hopefully I can add multiple properites.

    I'm simply going to tell it to, for each of the JButtons, putClientProperty("X value", Integer x), putClientProperty("Y value", Integer y), putClientProperty("Tool tip", String toolTip), putClientProperty("Color", Color c);
    Last edited by javapenguin; December 20th, 2011 at 09:46 PM.

  13. #12
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    Ok, I fixed all of that but now it seems I'm always hitting the battleship on every button. (I'm testing it with a kind of one player way first before going to getting a second player involved.) Also, all the exceptions seem to have gone away.

     
     
     
       import java.util.*;
       import javax.swing.*;
       import java.awt.event.*;
       import java.awt.*;
       import java.io.*;
     
       public class TwoDBattleshipGame implements ActionListener
       {
          private JSplitPane compPane, humPane;
          final private JPanel topCompPanel;
          final private JPanel bottomCompPanel;
          final private JPanel topHumPanel;
          final private JPanel bottomHumPanel;
          private HumanPlayer p1, p2;
          private ComputerPlayer cp;
          private JButton[][] humanGrid;
          private JButton[][] humanGrid2;
          private JButton[][] computerGrid;
          private int i, j;
          private JFrame contentHuman;
          private JDialog jf;
     
          public class SecondListenerClass implements ActionListener {
             public void actionPerformed(ActionEvent e)
             {
                JButton sjb = (JButton) e.getSource();
     
                if (p1.fire((Integer)sjb.getClientProperty("X value"),(Integer)sjb.getClientProperty("Y value")) == 'H')
                {
     
                   JOptionPane.showMessageDialog(null, "You sunk my battleship!");
     
                }
                else if (p1.fire((Integer)sjb.getClientProperty("X value"), (Integer)sjb.getClientProperty("Y value")) == 'M')
                {
                   JOptionPane.showMessageDialog(null,"Miss");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("M");
     
                }
     
                else if (p1.fire((Integer) sjb.getClientProperty("X value"),(Integer)sjb.getClientProperty("Y value")) == 'A' && humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].getText().equals("M"))
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("A");
     
     
                }
     
                else
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
     
                }
     
             }
          }
     
     
          public class FirstListenerClass implements ActionListener {
     
             private SecondListenerClass slc;
             public FirstListenerClass()
             {
                slc = new SecondListenerClass();
     
             }
             public void actionPerformed(ActionEvent e)
             {
     
                jf.setVisible(false);
                int gs = 0;
                boolean isValid = false;
                while (isValid == false)
                {
                   try
                   {
                      gs = Integer.parseInt(JOptionPane.showInputDialog ("Enter grid size.", "Enter grid size."));
                      isValid = true;
                   }
     
                      catch(NumberFormatException nfe)
                      {
                         JOptionPane.showMessageDialog(null,"Enter an integer.", "Error!", JOptionPane.ERROR_MESSAGE);
                      }
     
     
                }
     
                try
                {
                   humanGrid = new JButton[gs][gs];
     
                }
                   catch(NegativeArraySizeException nase)
                   {
                      gs = -gs;
                      humanGrid = new JButton[gs][gs];
                   }
     
                System.out.println(humanGrid);
                topHumPanel.setLayout(new GridLayout(gs,gs));
     
     
                String name = JOptionPane.showInputDialog("Enter name of player.", "Enter name of player.");
                p1 = new HumanPlayer(name, gs);
                String cpName = JOptionPane.showInputDialog("Enter name of computer player.", "Enter name of computer player.");
                cp = new ComputerPlayer(cpName, gs);
     
                int xLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter x location of battleship."));
                int yLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter y location of battleship."));
                p1.placeBattleship(xLoc,yLoc);
                cp.setOpposingX(xLoc);
                cp.setOpposingY(yLoc);
                cp.placeBattleship();
     
     
                for ( int i =0; i < humanGrid.length; i++)
                {
                   for ( int j = 0; j < humanGrid[i].length; j++)
                   {
                      Integer iValue = i;
                      Integer jValue = j;
                      humanGrid[i][j] = new JButton("?");
                      humanGrid[i][j].putClientProperty("X value", (Integer) i);
                      humanGrid[i][j].putClientProperty("Y value", (Integer) j);
                      humanGrid[i][j].setToolTipText("(" + iValue.toString() + "," + jValue.toString() + ")");
                      humanGrid[i][j].setBackground(Color.BLUE);
                      topHumPanel.add(humanGrid[i][j]);
                      humanGrid[i][j].addActionListener(slc);
                   }
                }
             }
          }
     
     
          protected class Player
          {
             private int x;
             private int y;
             private int opposingX;
             private int opposingY;
             private String name;
             private Integer shots;
             protected char[][] grid;
     
     
             public Player(String name)
             {
     
                setName(name);
                shots = 0;
     
             }
     
             public Player()
             {
                setName("John Doe");
                shots = 0;
             }
     
             public void setShots(Integer shots)
             {
                this.shots = shots;
             }
     
             public Integer getShots()
             {
                return shots;
             }
     
             public void setX(int x)
             {
                this.x = x;
             }
     
             public int getX()
             {
                return x;
             }
     
             public void setY(int y)
             {
                this.y = y;
             }
     
             public int getY()
             {
                return y;
             }
     
             public void setOpposingX(int opposingX)
             {
                this.opposingX = opposingX;
     
             }
     
             public int getOpposingX()
             {
                return opposingX;
             }
     
             public void setOpposingY(int opposingY)
             {
                this.opposingY = opposingY;
             }
     
             public int getOpposingY()
             {
                return opposingY;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
             public char fire(int x, int y)
             {
                if (grid[x][y] == grid[getOpposingX()][getOpposingY()])
                {  
                   setShots(getShots() + 1);
                   return 'H';
                }
                else
                {
                   if ((grid[x][y] != grid[getOpposingX()][getOpposingY()]) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      setShots(getShots() + 1);
                      return 'M';
     
                   }
                   else if (grid[x][y] == 'M')
                   {
                      grid[x][y] = 'A';
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                   else
                   {
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                }
             }
     
          }
     
          private class HumanPlayer extends Player
          {
     
             private int size;
     
             public HumanPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
     
             }
     
             private void setGridSize(int size)
             {
                this.size = size;
             }
     
             private int getGridSize()
             {
                return size;
             }
     
     
     
             public HumanPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
     
             }
     
             public void placeBattleship(int x, int y)
             {
                setX(x);
                setY(y);
     
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
     
          }
     
          private class ComputerPlayer extends Player
          {
     
             private int size;
     
             public ComputerPlayer(String name, int size)
             {
                super(name);
                setGridSize(size);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public ComputerPlayer()
             {
                super();
                setGridSize(10);
                grid = new char[10][10];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public void setGridSize(int size)
             {
                this.size = size;
             }
     
             public int getGridSize()
             {
                return size;
             }
     
             public char[][] getGrid()
             {
                return grid;
             }
     
             public void placeBattleship()
             {
     
                int x = (int) (Math.random() * grid.length);
                int y = (int) (Math.random() * grid.length);
     
                setX(x);
                setY(y);
     
             }
          }
     
          public TwoDBattleshipGame()
          {
             contentHuman = new JFrame("Human Player");
             FirstListenerClass flc = new FirstListenerClass();
             jf = new JDialog();
             jf.setTitle("Select an option.");
             jf.setVisible(true);
             ButtonGroup bg = new ButtonGroup();
             JRadioButton option1 = new JRadioButton("Human vs. Computer");
             JRadioButton option2 = new JRadioButton("Human vs. Human");
             bg.add(option1);
             bg.add(option2);
             jf.add(option1);
             jf.add(option2);
             jf.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
             JDialog.setDefaultLookAndFeelDecorated(true);
             jf.add(option1);
             jf.add(option2);
             jf.setLayout(new GridLayout(2,1));
             jf.setMinimumSize(new Dimension(200,200));
             jf.setResizable(false);
             jf.setBackground(Color.GREEN);
             topHumPanel = new JPanel();
             topCompPanel = new JPanel();
             bottomCompPanel = new JPanel();
             bottomHumPanel = new JPanel();
             humPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topHumPanel, bottomHumPanel);
             humPane.setVisible(true);
             contentHuman.setContentPane(humPane);
             contentHuman.setVisible(true);
             contentHuman.setMinimumSize(new Dimension(300,300));
             option1.addActionListener(flc);
     
     
     
     
     
     
     
             option2.addActionListener(
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                      }});
     
     
     
     
          }
     
          public void setHumanP1I(int i)
          {
             this.i = i;
          }
     
          public int getHumanP1I()
          {
             return i;
          }
     
          public void setHumanP1J(int j)
          {
             this.j = j;
          }
     
          public int getHumanP1J()
          {
             return j;
          }
     
          public static void main(String[] args)
          {
     
             JOptionPane.showMessageDialog(null, "Welcome to Battleship Game.", "Welcome", JOptionPane.INFORMATION_MESSAGE);
             new TwoDBattleshipGame();
     
          }
     
          public void actionPerformed(ActionEvent e)
          {
     
     
          }
       }
    Last edited by javapenguin; December 20th, 2011 at 10:18 PM.

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    Have you tried debugging your code to check the values of the variables that are used by adding printlns to show them as the code executes?

  15. #14
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    It appears to be always going into the "Hit" part of the fire method. Is there something wrong with my phrasing in the code?

  16. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to create a battleship game but am having ActionListener issues due to sco

    Have you tried debugging your code to check the values of the variables that are used by adding printlns to show them as the code executes?

  17. #16
    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: Trying to create a battleship game but am having ActionListener issues due to sco



    I think I found the problem.

    if (grid[x][y] == grid[getOpposingX()][getOpposingY()])

    I'll fix that and see what happens after that.

    Ok, now it'll hit it only when it gets the exact spot but somehow, perhaps due to some or's instead of ands, it will say "Already shot there!" if it's in the same vertical value (same y value) as the actual battleship location.

    public char fire(int x, int y)
             {
                if (x == getOpposingX() && y == getOpposingY())
                {  
     
                   System.out.println("Oops I did it again!");
                   setShots(getShots() + 1);
                   return 'H';
                }
                else
                {
                   if (((x != getOpposingX()) || (y != getOpposingY())) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      setShots(getShots() + 1);
                      return 'M';
     
                   }
                   else if ((x != getOpposingX()) || (y != getOpposingY()) && grid[x][y] == 'M')
                   {
                      grid[x][y] = 'A';
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                   else
                   {
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
              }
         }

    Even worse, now it's returning "Already shot there." for all but a direct battleship hit.

    Not sure if the problem is in the listener or in the fire method, but probably in the fire method.

     
     
       import java.util.*;
       import javax.swing.*;
       import java.awt.event.*;
       import java.awt.*;
       import java.io.*;
     
       public class TwoDBattleshipGame implements ActionListener
       {
          private JSplitPane compPane, humPane;
          final private JPanel topCompPanel;
          final private JPanel bottomCompPanel;
          final private JPanel topHumPanel;
          final private JPanel bottomHumPanel;
          private HumanPlayer p1, p2;
          private ComputerPlayer cp;
          private JButton[][] humanGrid;
          private JButton[][] humanGrid2;
          private JButton[][] computerGrid;
          private int i, j;
          private JFrame contentHuman;
          private JDialog jf;
          private JLabel shotsLabel;
          private JTextField shots;
          private JButton quit, reveal;
          private JMenuBar p1MBar, p2MBar;
          private JMenu p1File, p2File;
          private JMenu p1Help, p2Help, p1Save2, p2Save2;
          private JMenuItem p1Save, p1Load, p2Save, p1SaveAs, p2SaveAs, p2Load, p1Exit, p2Exit, p1HighScore, p2HighScore;
          private JMenuItem p1Help2, p2Help2;
          private JScrollPane p1ScrollPane;
          private QuitListener ql;
     
     
          public class SecondListenerClass implements ActionListener {
             public void actionPerformed(ActionEvent e)
             {
                JButton sjb = (JButton) e.getSource();
     
                if (p1.fire((Integer)(sjb.getClientProperty("X value")),(Integer)(sjb.getClientProperty("Y value"))) == 'H')
                {
                   System.out.println("X Value: " + sjb.getClientProperty("X value"));
                   System.out.println("Y Value: " + sjb.getClientProperty("Y value"));		
                   sjb.setText("H");		
                   JOptionPane.showMessageDialog(null, "You sunk my battleship!");
     
                }
                else if (p1.fire((Integer)sjb.getClientProperty("X value"), (Integer)sjb.getClientProperty("Y value")) == 'M')
                {
                   JOptionPane.showMessageDialog(null,"Miss");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("M");
     
                }
     
                else if (p1.fire((Integer) sjb.getClientProperty("X value"),(Integer)sjb.getClientProperty("Y value")) == 'A' && humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].getText().equals("M"))
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("A");
     
     
                }
     
                else
                {
                   JOptionPane.showMessageDialog(null, "Already shot there.");
     
                }
     
             }
          }
     
     
          public class FirstListenerClass implements ActionListener {
     
             private SecondListenerClass slc;
             public FirstListenerClass()
             {
                slc = new SecondListenerClass();
     
             }
             public void actionPerformed(ActionEvent e)
             {
     
                jf.setVisible(false);
                int gs = 0;
                boolean isValid = false;
                while (isValid == false)
                {
                   try
                   {
                      gs = Integer.parseInt(JOptionPane.showInputDialog ("Enter grid size.", "Enter grid size."));
                      if (gs == 0 || gs > 30 || gs < -30)
                         throw new SizeOutOfRangeException();
                      isValid = true;
                   }
     
                      catch(NumberFormatException nfe)
                      {
                         JOptionPane.showMessageDialog(null,"Enter an integer.", "Error!", JOptionPane.ERROR_MESSAGE);
                      }
     
                      catch(SizeOutOfRangeException soore)
                      {
                         JOptionPane.showMessageDialog(null, soore.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
     
                      }
     
     
                }
     
                try
                {
                   humanGrid = new JButton[gs][gs];
     
                }
                   catch(NegativeArraySizeException nase)
                   {
                      gs = -gs;
                      humanGrid = new JButton[gs][gs];
                   }
     
                System.out.println(humanGrid);
                topHumPanel.setLayout(new GridLayout(gs,gs));
     
     
                String name = JOptionPane.showInputDialog("Enter name of player.", "Enter name of player.");
                p1 = new HumanPlayer(name, gs, 1);
                String cpName = JOptionPane.showInputDialog("Enter name of computer player.", "Enter name of computer player.");
                cp = new ComputerPlayer(cpName, gs);
     
                int xLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter x location of battleship."));
                int yLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter y location of battleship."));
                p1.placeBattleship(xLoc,yLoc);
                cp.setOpposingX(xLoc);
                cp.setOpposingY(yLoc);
                cp.placeBattleship();
                p1.setOpposingX(cp.getX());
                p1.setOpposingY(cp.getY());
                System.out.println("Placed battleship.");
     
     
     
                for ( int i =0; i < humanGrid.length; i++)
                {
                   for ( int j = 0; j < humanGrid[i].length; j++)
                   {
                      Integer iValue = i;
                      Integer jValue = j;
                      humanGrid[i][j] = new JButton("?");
                      humanGrid[i][j].putClientProperty("X value", (Integer) i);
                      humanGrid[i][j].putClientProperty("Y value", (Integer) j);
                      humanGrid[i][j].setToolTipText("(" + iValue.toString() + "," + jValue.toString() + ")");
                      humanGrid[i][j].setBackground(Color.BLUE);
                      topHumPanel.add(humanGrid[i][j]);
                      humanGrid[i][j].addActionListener(slc);
                   }
                }
             }
          }
     
     
          protected class Player
          {
             private int x;
             private int y;
             private int opposingX;
             private int opposingY;
             private String name;
             private Integer shots;
             protected char[][] grid;
             protected int size;
     
     
     
             public Player(String name,int size)
             {
     
                setName(name);
                setGridSize(size);
                shots = 0;
     
     
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public Player()
             {
                setName("John Doe");
                shots = 0;
                size = 10;
                setGridSize(10);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
     
     
             public void setShots(Integer shots)
             {
                this.shots = shots;
             }
     
             public Integer getShots()
             {
                return shots;
             }
     
             public void setX(int x)
             {
                this.x = x;
             }
     
             public int getX()
             {
                return x;
             }
     
             public void setY(int y)
             {
                this.y = y;
             }
     
             public int getY()
             {
                return y;
             }
     
             public void setOpposingX(int opposingX)
             {
                this.opposingX = opposingX;
     
             }
     
             protected void setGridSize(int size)
             {
                this.size = size;
             }
     
             protected int getGridSize()
             {
                return size;
             }
     
             public int getOpposingX()
             {
                return opposingX;
             }
     
             public void setOpposingY(int opposingY)
             {
                this.opposingY = opposingY;
             }
     
             public int getOpposingY()
             {
                return opposingY;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
             public char fire(int x, int y)
             {
                if (x == getOpposingX() && y == getOpposingY())
                {  
     
                   System.out.println("Oops I did it again!");
                   setShots(getShots() + 1);
                   return 'H';
                }
                else
                {
                   if (((x != getOpposingX()) || (y != getOpposingY()) || (x!= getOpposingX() && y != getOpposingY())) && (grid[x][y] == '?'))
                   {
                      grid[x][y] = 'M';
                      setShots(getShots() + 1);
                      return 'M';
     
                   }
                   else if (((x != getOpposingX()) || (y != getOpposingY())) && (grid[x][y] == 'M'))
                   {
                      grid[x][y] = 'A';
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                   else
                   {
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                }
             }
     
             protected char[][] getGrid()
             {
                return grid;
             }
          }
     
          private class HumanPlayer extends Player
          {
             private int playerNumber;
     
             //private int size;
     
             public HumanPlayer(String name, int size, int playerNumber)
             {
                super(name,size);
                setPlayerNumber(playerNumber);
     
     
             }
     
     
     
     
     
             public HumanPlayer()
             {
                super();
                setPlayerNumber(1);
     
             }
     
             public void setPlayerNumber(int playerNumber)
             {
                this.playerNumber = playerNumber;
             }
     
             public int getPlayerNumber()
             {
                return playerNumber;
             }
     
             public void placeBattleship(int x, int y)
             {
                setX(x);
                setY(y);
     
             }
     
     
     
     
          }
     
          private class ComputerPlayer extends Player
          {
     
             //private int size;
     
             public ComputerPlayer(String name, int size)
             {
                super(name,size);
     
             }
     
             public ComputerPlayer()
             {
                super();
     
             }
     
     
             public void placeBattleship()
             {
     
                int x = (int) (Math.random() * grid.length);
                int y = (int) (Math.random() * grid.length);
     
                setX(x);
                setY(y);
     
             }
     
     
          }
     
          public TwoDBattleshipGame()
          {
             ql = new QuitListener();
             contentHuman = new JFrame("Human Player");
             p1MBar = new JMenuBar();
             FirstListenerClass flc = new FirstListenerClass();
             jf = new JDialog();
             jf.setTitle("Select an option.");
             jf.setVisible(true);
             ButtonGroup bg = new ButtonGroup();
             JRadioButton option1 = new JRadioButton("Human vs. Computer");
             JRadioButton option2 = new JRadioButton("Human vs. Human");
             bg.add(option1);
             bg.add(option2);
             jf.add(option1);
             jf.add(option2);
             jf.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
             JDialog.setDefaultLookAndFeelDecorated(true);
             jf.add(option1);
             jf.add(option2);
             jf.setLayout(new GridLayout(2,1));
             jf.setMinimumSize(new Dimension(200,200));
             jf.setResizable(false);
             jf.setBackground(Color.GREEN);
             topHumPanel = new JPanel();
             p1ScrollPane = new JScrollPane(topHumPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             topCompPanel = new JPanel();
             bottomCompPanel = new JPanel();
             bottomHumPanel = new JPanel();
             shotsLabel = new JLabel("Shots:");
             shots = new JTextField(11);
             shots.setText("0");
     
             humPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, p1ScrollPane, bottomHumPanel);
             humPane.setVisible(true);
             contentHuman.setContentPane(humPane);
             contentHuman.setVisible(true);
             contentHuman.setMinimumSize(new Dimension(300,300));
             option1.addActionListener(flc);
     
             reveal = new JButton("Reveal Battleship.");
             quit = new JButton("Quit");
     
             reveal.addActionListener(this);
             quit.addActionListener(ql);
             bottomHumPanel.add(shotsLabel);
             shots.setEditable(false);
             bottomHumPanel.add(shots);
             bottomHumPanel.add(reveal);
             bottomHumPanel.add(quit);
             bottomHumPanel.setLayout(new GridLayout(2,2));
             contentHuman.setJMenuBar(p1MBar);
             p1File = new JMenu("File");
             p1MBar.add(p1File);                  
             p1Save2 = new JMenu("Save");
             p1File.add(p1Save2);            
             p1Save = new JMenuItem("Save");
             p1SaveAs = new JMenuItem("Save As");
             p1Save2.add(p1SaveAs);
             p1Save2.addSeparator();
             p1Save2.add(p1Save);          
             p1File.addSeparator();  
             p1Load = new JMenuItem("Open");
             p1File.add(p1Load);
             p1File.addSeparator();
             p1Exit = new JMenuItem("Exit");
             p1File.add(p1Exit);
             p1Exit.addActionListener(ql);
             p1File.addSeparator();
     
             option2.addActionListener(
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                      }});
     
     
     
     
          }
     
          public int Human1ShotsToInt()
          {
             return (Integer.parseInt(shots.getText()));
     
          }
     
          public String Human1ShotsToString()
          {
             Integer h1Shots = p1.getShots();
             return h1Shots.toString();
          }
     
     
          public void setHumanP1I(int i)
          {
             this.i = i;
          }
     
          public int getHumanP1I()
          {
             return i;
          }
     
          public void setHumanP1J(int j)
          {
             this.j = j;
          }
     
          public int getHumanP1J()
          {
             return j;
          }
     
          public static void main(String[] args)
          {
     
             JOptionPane.showMessageDialog(null, "Welcome to Battleship Game.", "Welcome", JOptionPane.INFORMATION_MESSAGE);
             new TwoDBattleshipGame();
     
          }
     
          public class QuitListener implements ActionListener
          {
     
             public void actionPerformed(ActionEvent e)
             {
                Object options[] = new Object[2];
                options[0] = "Yes";
                options[1] = "No. Clicked this button by mistake.";
     
                int m = JOptionPane.showOptionDialog(null, "Are you sure you want to quit?", "Quit?",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,  options , options[0]);
                if (m == JOptionPane.YES_OPTION)
                   System.exit(0);
             }
     
          }
          public void actionPerformed(ActionEvent e)
          {
     
             if (e.getActionCommand().equals("Quit"))
             {
                Object options[] = new Object[2];
                options[0] = "Yes";
                options[1] = "No. Clicked thsi button by mistake.";
     
                int m = JOptionPane.showOptionDialog(null, "Are you sure you wnat to quit?", "Quit?",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,  options , options[0]);
                if (m == JOptionPane.YES_OPTION)
                   System.exit(0);
     
             }
     
          }
       }

    SizeOutOfRangeException.java
       public class SizeOutOfRangeException extends Exception
       {
     
          public SizeOutOfRangeException()
          {
     
             super("The size is out of range or is 0.  Please choose a valid size.");
     
          }
     
          public SizeOutOfRangeException(String message)
          {
             super(message);
          }
     
       }
    Last edited by javapenguin; December 21st, 2011 at 05:47 PM.

  18. #17
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    Ok, I've added some printlns and found something strange.

    It seems if I miss the battleship, when it goes to the fire method, it's somehow going through the block that contains the miss, the block that contains the first already shot there, and then through the subsequent already shot there block. this all for one single shot. I then tried firing there again and found it going through the last (the one for subsequent already shot theres) block three times in one go.

    It appears to be going to the last part of the listener only, indicating, as I already suspected, that something is going wrong in the fire method that is always causing them to somehow go through all of the blocks, despite my return statements that should be stopping that.

    I've did a test to see what happens if, for some odd reason, more than one block could evaluate to true. I found it only goes to the first block. (This test was independent of the battleship game. It was something like this:

    int i = 2;

    if (i == 2)
    System.out.println("What happens when two blocks are true?");
    else if (i < 3)
    System.out.println("Let's find out.");
    else if (i > -1)
    System.out.println("Have fun!");
    And it only went to the first one despite all being true. I'm assuming it would only go to the second one if the first was false.

    Hmmmmmmm.....what if it's going through the fire method three times at once due to something else going wrong, perhaps in the listener?
    The listener is calling the fire method.

    I've found something odd:
    I'm wondering, every time it crosses the blocks, if it comes across a statement that isn't true in the listener, then is it calling the fire method anyway, hence why, if it's always going to the last one, it appears to be going through it three times?

    Yes, it's definitely calling that method three times. I did a silly test in another program and found that yes, every time I call a method, it will execute it, even if only used in an if statement. So I have to deal with that in addition to figuring out why the listener is only going to the last block in the listener every time.
    Last edited by javapenguin; December 22nd, 2011 at 01:27 PM.

  19. #18
    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: Trying to create a battleship game but am having ActionListener issues due to sco

    Ok, I fixed that problem but now I had decided to try and make there be only one interface, albeit two separate instances, for the player in the case of two players rather than having to design two identical player UIs and wasting a lot of space and time. However, I cannot figure out how to increment the shot counter in a way that won't increment all the shot counters.

    Also, often my variables were defined inside ActionListeners and I cannot access them in the actual constructor of the main class. I suppose I could simply add getter and setter methods though how it would know which Player to increment and update, I'm not sure.

    As if that weren't enough, in my second one, despite setting a layout what should be correct, only 1 button is showing up in the top panel.

     
     
       import java.util.*;
       import javax.swing.*;
       import java.awt.event.*;
       import java.awt.*;
       import java.io.*;
     
       public class TwoDBattleshipGame implements ActionListener
       {
          private JSplitPane compPane, humPane;
          final private JPanel topCompPanel;
          final private JPanel bottomCompPanel;
          final private JPanel topHumPanel;
          final private JPanel bottomHumPanel;
          private HumanPlayer p1, p2;
          private ComputerPlayer cp;
          private JButton[][] humanGrid;
          private JButton[][] humanGrid2;
          private JButton[][] computerGrid;
          private BattleshipHumanPlayerUI bhpui;
          private int i, j;
          private JFrame contentHuman;
          private JDialog jf;
          private JLabel shotsLabel;
          private JTextField shots;
          private JButton quit, reveal;
          private JMenuBar p1MBar, p2MBar;
          private JMenu p1File, p2File;
          private JMenu p1Help, p2Help, p1Save2, p2Save2;
          private JMenuItem p1Save, p1Load, p2Save, p1SaveAs, p2SaveAs, p2Load, p1Exit, p2Exit, p1HighScore, p2HighScore;
          private JMenuItem p1Help2, p2Help2;
          private JScrollPane p1ScrollPane;
          private QuitListener ql;
          private BattleshipPlayerUI bpui;
          private BattleshipPlayerUI bpui2;
     
     
          protected class BattleshipPlayerUI extends JFrame
          {
             protected JPanel topPanel;
             protected JPanel bottomPanel;
             protected JButton[][] grid;
             protected JScrollPane scrollPane;
             protected JLabel shotsLabel;
             protected JTextField shots;
             protected int size;
             protected String name;
             protected SecondListenerClass slc;
             protected int shots2;
             protected JSplitPane contentPane;
     
     
             public BattleshipPlayerUI()
             {
     
     
             }
             public BattleshipPlayerUI(String name, int size)
             {
                setName(name);
                setTitle(getName());
                setShots(0);
                slc = new SecondListenerClass();
                setGridSize(size);
                grid = new JButton[size][size];
                topPanel = new JPanel();
                scrollPane = new JScrollPane(topPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
     
                //topPanel.setLayout(new GridLayout(size,size));
                for (int i =0; i < grid.length; i++)
                {
     
                   for (int j =0; j < grid[i].length; j++)
                   {
                      Integer iValue = i;
                      Integer jValue = j;
                      grid[i][j] = new JButton("?");
                      grid[i][j].putClientProperty("X value", (Integer) i);
                      grid[i][j].putClientProperty("Y value", (Integer) j);
                      grid[i][j].setToolTipText("(" + iValue.toString() + "," + jValue.toString() + ")");
                      grid[i][j].setBackground(Color.BLUE);
                      topPanel.add(grid[i][j]);
                      grid[i][j].addActionListener(slc);
     
     
                   }
                }
                shotsLabel = new JLabel("Shots:");
     
                bottomPanel = new JPanel();
                //topPanel.setLayout(new GridLayout(size,size));
                contentPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane, bottomPanel);
                shots = new JTextField(11);
                shots.setEditable(false);
                shots.setText("0");
                bottomPanel.add(shotsLabel);
                bottomPanel.add(shots);
                topPanel.setLayout(new GridLayout(size,size));
                setContentPane(contentPane);
     
     
             }
     
             public JTextField getShotsField()
             {
                return shots;
             }
     
             public JSplitPane getSplitPane()
             {
                return contentPane;
             }
     
             public JPanel getTopPanel()
             {
                return topPanel;
             }
     
             public JPanel getBottomPanel()
             {
                return bottomPanel;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
             public void setGridSize(int size)
             {
                this.size = size;
             }
     
             public int getGridSize()
             {
                return size;
             }
     
             public JButton[][] getGrid()
             {
                return grid;
             }
     
             public void setShots(int shots2)
             {
                this.shots2 = shots2;
             }
     
             public int getShots()
             {
                return shots2;
             }
     
     
          }
          private class BattleshipComputerPlayerUI extends JSplitPane
          {
             private JPanel topCompPanel;
             private JPanel bottomCompPanel;
             private JScrollPane scrollPane;
             private JButton[][] computerGrid;
             private JLabel shotsLabel;
     
             public BattleshipComputerPlayerUI(String name, int size)
             {
                computerGrid = new JButton[size][size];
     
     
             }
             public JLabel getShotsLabel()
             {
                return shotsLabel;
             }
     
     
          }
     
          private class BattleshipHumanPlayerUI extends BattleshipPlayerUI
          {
             private Integer playerNumber;
             private JPanel topHumPanel;
             private JButton reveal;
             private JButton quit;
             private QuitListener ql;
     
             public BattleshipHumanPlayerUI(Integer playerNumber)
             {
     
                this.playerNumber = playerNumber;
                topHumPanel = new JPanel();
                reveal = new JButton("Reveal Battleship");
                quit = new JButton("Quit");
                ql = new QuitListener();
                quit.addActionListener(ql);
     
     
     
                if (playerNumber == 1)
                   getSplitPane().putClientProperty("Player 1", playerNumber);
                else if (playerNumber == 2)
                   getSplitPane().putClientProperty("Player 2", playerNumber);
                else
                   getSplitPane().putClientProperty("Invalid", playerNumber);
     
                setTopPanel(topHumPanel);
     
     
             }
     
             public void setTopPanel(JPanel topHumPanel)
             {
                this.topHumPanel = topHumPanel;
             }
     
             public JPanel getTopPanel()
             {
                return topHumPanel;
             }
     
     
          }
     
          public class SecondListenerClass implements ActionListener {
             public void actionPerformed(ActionEvent e)
             {
                JButton sjb = (JButton) e.getSource();
     
     
                char value = p1.fire((Integer)(sjb.getClientProperty("X value")),(Integer)(sjb.getClientProperty("Y value")));
                if (value == 'H')
                {
                   System.out.println("X Value: " + sjb.getClientProperty("X value"));
                   System.out.println("Y Value: " + sjb.getClientProperty("Y value"));		
                   sjb.setText("H");		
                   JOptionPane.showMessageDialog(null, "You sunk my battleship!");
     
     
                }
                else if (value == 'M')
                {
                   JOptionPane.showMessageDialog(null,"Miss");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("M");
     
     
                }
     
                else if (value == 'A' && humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].getText().equals("M"))
                {
                   System.out.println("Is it going here?");
                   JOptionPane.showMessageDialog(null, "Already shot there.");
                   humanGrid[(Integer)sjb.getClientProperty("X value")][(Integer)sjb.getClientProperty("Y value")].setText("A");
     
     
     
                }
     
                else
                {
                   System.out.println("Or is it going here always?");
                   JOptionPane.showMessageDialog(null, "Already shot there.");
     
                }
     
             }
          }
     
     
          public class FirstListenerClass implements ActionListener {
     
             private SecondListenerClass slc;
             public FirstListenerClass()
             {
                slc = new SecondListenerClass();
     
             }
             public void actionPerformed(ActionEvent e)
             {
     
                jf.setVisible(false);
                int gs = 0;
                boolean isValid = false;
                while (isValid == false)
                {
                   try
                   {
                      gs = Integer.parseInt(JOptionPane.showInputDialog ("Enter grid size.", "Enter grid size."));
                      if (gs == 0 || gs > 30 || gs < -30)
                         throw new SizeOutOfRangeException();
                      isValid = true;
                   }
     
                      catch(NumberFormatException nfe)
                      {
                         JOptionPane.showMessageDialog(null,"Enter an integer.", "Error!", JOptionPane.ERROR_MESSAGE);
                      }
     
                      catch(SizeOutOfRangeException soore)
                      {
                         JOptionPane.showMessageDialog(null, soore.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
     
                      }
     
     
                }
     
                try
                {
                   humanGrid = new JButton[gs][gs];
     
                }
                   catch(NegativeArraySizeException nase)
                   {
                      gs = -gs;
                      humanGrid = new JButton[gs][gs];
                   }
     
                System.out.println(humanGrid);
                topHumPanel.setLayout(new GridLayout(gs,gs));
     
     
                String name = JOptionPane.showInputDialog("Enter name of player.", "Enter name of player.");
                p1 = new HumanPlayer(name, gs, 1);
                bpui = new BattleshipPlayerUI(p1.getName(), p1.getPlayerNumber());
                bpui.setVisible(true);
                String cpName = JOptionPane.showInputDialog("Enter name of computer player.", "Enter name of computer player.");
                cp = new ComputerPlayer(cpName, gs);
     
                int xLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter x location of battleship."));
                int yLoc = Integer.parseInt(JOptionPane.showInputDialog("Enter y location of battleship."));
                p1.placeBattleship(xLoc,yLoc);
                cp.setOpposingX(xLoc);
                cp.setOpposingY(yLoc);
                cp.placeBattleship();
                p1.setOpposingX(cp.getX());
                p1.setOpposingY(cp.getY());
                System.out.println("Placed battleship.");
     
     
     
                for ( int i =0; i < humanGrid.length; i++)
                {
                   for ( int j = 0; j < humanGrid[i].length; j++)
                   {
                      Integer iValue = i;
                      Integer jValue = j;
                      humanGrid[i][j] = new JButton("?");
                      humanGrid[i][j].putClientProperty("X value", (Integer) i);
                      humanGrid[i][j].putClientProperty("Y value", (Integer) j);
                      humanGrid[i][j].setToolTipText("(" + iValue.toString() + "," + jValue.toString() + ")");
                      humanGrid[i][j].setBackground(Color.BLUE);
                      topHumPanel.add(humanGrid[i][j]);
                      humanGrid[i][j].addActionListener(slc);
                   }
                }
             }
          }
     
     
          protected class Player
          {
             private int x;
             private int y;
             private int opposingX;
             private int opposingY;
             private String name;
             private Integer shots;
             protected char[][] grid;
             protected int size;
     
     
     
             public Player(String name,int size)
             {
     
                setName(name);
                setGridSize(size);
                shots = 0;
     
     
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
             public Player()
             {
                setName("John Doe");
                shots = 0;
                size = 10;
                setGridSize(10);
                grid = new char[getGridSize()][getGridSize()];
                for (int i = 0; i < grid.length; i++)
                {
                   for (int j = 0; j < grid[i].length; j++)
                      grid[i][j] = '?';
     
     
                }
             }
     
     
     
             public void setShots(Integer shots)
             {
                this.shots = shots;
             }
     
             public Integer getShots()
             {
                return shots;
             }
     
             public void setX(int x)
             {
                this.x = x;
             }
     
             public int getX()
             {
                return x;
             }
     
             public void setY(int y)
             {
                this.y = y;
             }
     
             public int getY()
             {
                return y;
             }
     
             public void setOpposingX(int opposingX)
             {
                this.opposingX = opposingX;
     
             }
     
             protected void setGridSize(int size)
             {
                this.size = size;
             }
     
             protected int getGridSize()
             {
                return size;
             }
     
             public int getOpposingX()
             {
                return opposingX;
             }
     
             public void setOpposingY(int opposingY)
             {
                this.opposingY = opposingY;
             }
     
             public int getOpposingY()
             {
                return opposingY;
             }
     
             public void setName(String name)
             {
                this.name = name;
             }
     
             public String getName()
             {
                return name;
             }
     
             public char fire(int x, int y)
             {
                if (x == getOpposingX() && y == getOpposingY())
                {  
     
                   System.out.println("Oops I did it again!");
                   setShots(getShots() + 1);
                   return 'H';
                }
                else 
                {
                   if (((x != getOpposingX()&& y != getOpposingY()) || (x == getOpposingX() && y != getOpposingY()) || (x != getOpposingX() && y == getOpposingY())) && grid[x][y] == '?')
                   {
                      System.out.println("Miss!");
                      grid[x][y] = 'M';
                      setShots(getShots() + 1);
                      return 'M';
     
                   }
                   else if ( ((x != getOpposingX()&& y != getOpposingY()) || (x == getOpposingX() && y != getOpposingY()) || (x != getOpposingX() && y == getOpposingY())) && grid[x][y] == 'M')
                   {
                      System.out.println("First already shot there.");
                      grid[x][y] = 'A';
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                   else
                   {
                      System.out.println("It's going here.");
                      setShots(getShots() + 1);
                      return 'A';
     
                   }
     
                }
             }
     
             protected char[][] getGrid()
             {
                return grid;
             }
          }
     
          private class HumanPlayer extends Player
          {
             private int playerNumber;
     
             //private int size;
     
             public HumanPlayer(String name, int size, int playerNumber)
             {
                super(name,size);
                setPlayerNumber(playerNumber);
     
     
             }
     
     
     
     
     
             public HumanPlayer()
             {
                super();
                setPlayerNumber(1);
     
             }
     
             public void setPlayerNumber(int playerNumber)
             {
                this.playerNumber = playerNumber;
             }
     
             public int getPlayerNumber()
             {
                return playerNumber;
             }
     
             public void placeBattleship(int x, int y)
             {
                setX(x);
                setY(y);
     
             }
     
     
     
     
          }
     
          private class ComputerPlayer extends Player
          {
     
             //private int size;
     
             public ComputerPlayer(String name, int size)
             {
                super(name,size);
     
             }
     
             public ComputerPlayer()
             {
                super();
     
             }
     
     
             public void placeBattleship()
             {
     
                int x = (int) (Math.random() * grid.length);
                int y = (int) (Math.random() * grid.length);
     
                setX(x);
                setY(y);
     
             }
     
     
          }
     
          public TwoDBattleshipGame()
          {
             ql = new QuitListener();
             contentHuman = new JFrame("Human Player");
             p1MBar = new JMenuBar();
             FirstListenerClass flc = new FirstListenerClass();
             jf = new JDialog();
             jf.setTitle("Select an option.");
             jf.setVisible(true);
             ButtonGroup bg = new ButtonGroup();
             JRadioButton option1 = new JRadioButton("Human vs. Computer");
             JRadioButton option2 = new JRadioButton("Human vs. Human");
             bg.add(option1);
             bg.add(option2);
             jf.add(option1);
             jf.add(option2);
             jf.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
             JDialog.setDefaultLookAndFeelDecorated(true);
             jf.add(option1);
             jf.add(option2);
             jf.setLayout(new GridLayout(2,1));
             jf.setMinimumSize(new Dimension(200,200));
             jf.setResizable(false);
             jf.setBackground(Color.GREEN);
             topHumPanel = new JPanel();
             p1ScrollPane = new JScrollPane(topHumPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             topCompPanel = new JPanel();
             bottomCompPanel = new JPanel();
             bottomHumPanel = new JPanel();
             shotsLabel = new JLabel("Shots:");
             shots = new JTextField(11);
             shots.setText("0");
             humPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, p1ScrollPane, bottomHumPanel);
             humPane.setVisible(true);
             contentHuman.setContentPane(humPane);
             contentHuman.setVisible(true);
             contentHuman.setMinimumSize(new Dimension(300,300));
             option1.addActionListener(flc);
     
             reveal = new JButton("Reveal Battleship.");
             quit = new JButton("Quit");
     
             reveal.addActionListener(this);
             quit.addActionListener(ql);
             bottomHumPanel.add(shotsLabel);
             shots.setEditable(false);
             bottomHumPanel.add(shots);
             bottomHumPanel.add(reveal);
             bottomHumPanel.add(quit);
             bottomHumPanel.setLayout(new GridLayout(2,2));
             contentHuman.setJMenuBar(p1MBar);
             p1File = new JMenu("File");
             p1MBar.add(p1File);                  
             p1Save2 = new JMenu("Save");
             p1File.add(p1Save2);            
             p1Save = new JMenuItem("Save");
             p1SaveAs = new JMenuItem("Save As");
             p1Save2.add(p1SaveAs);
             p1Save2.addSeparator();
             p1Save2.add(p1Save);          
             p1File.addSeparator();  
             p1Load = new JMenuItem("Open");
             p1File.add(p1Load);
             p1File.addSeparator();
             p1Exit = new JMenuItem("Exit");
             p1File.add(p1Exit);
             p1Exit.addActionListener(ql);
             p1File.addSeparator();
     
     
             option2.addActionListener(
                   new ActionListener() {
     
                      public void actionPerformed(ActionEvent e)
                      {
     
                      }});
     
     
     
     
          }
     
          public int Human1ShotsToInt()
          {
             return (Integer.parseInt(shots.getText()));
     
          }
     
          public String Human1ShotsToString()
          {
             Integer h1Shots = p1.getShots();
             return h1Shots.toString();
          }
     
     
     
     
          public static void main(String[] args)
          {
     
             JOptionPane.showMessageDialog(null, "Welcome to Battleship Game.", "Welcome", JOptionPane.INFORMATION_MESSAGE);
             new TwoDBattleshipGame();
     
          }
     
          public class QuitListener implements ActionListener
          {
     
             public void actionPerformed(ActionEvent e)
             {
                Object options[] = new Object[2];
                options[0] = "Yes";
                options[1] = "No. Clicked this button by mistake.";
     
                int m = JOptionPane.showOptionDialog(null, "Are you sure you want to quit?", "Quit?",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,  options , options[0]);
                if (m == JOptionPane.YES_OPTION)
                   System.exit(0);
             }
     
          }
          public void actionPerformed(ActionEvent e)
          {
     
             if (e.getActionCommand().equals("Quit"))
             {
                Object options[] = new Object[2];
                options[0] = "Yes";
                options[1] = "No. Clicked thsi button by mistake.";
     
                int m = JOptionPane.showOptionDialog(null, "Are you sure you wnat to quit?", "Quit?",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,  options , options[0]);
                if (m == JOptionPane.YES_OPTION)
                   System.exit(0);
     
             }
     
          }
       }

    A lot of things in there are redundant as I was in the process of [I] trying [/B] to make things more efficient and reduce coding.

    I'm wondering if, instead of having FirstListenerClass, I should do something like a loop or something inside the constructor of the main class, to ensure that stuff happens only after the person has selected one of the two options that initially show up. That way they won't go out of scope.

    But I've no idea how to maintain scoping and efficiency both.


    ----edit------

    I found by fiddling with the GUIs that the one JButton that is showing on the do-over BattleshipUI is corresponding exactly to the button at 0,0 in the other one that is fully (minus the shot counter) functional but which has to be redone to avoid needed to recreate the components all over again for each of the potential two players (not to mention the computer.)

    A shot at the one JButton in the newer one is updating the older one as well and I'm wondering why.

    Merry Christmas!
    Last edited by javapenguin; December 24th, 2011 at 12:39 AM.

Similar Threads

  1. Simple game that requires me to load game settings from a file
    By 14fenix in forum Java Theory & Questions
    Replies: 5
    Last Post: December 1st, 2011, 09:21 PM
  2. Help with ActionListener please
    By knightmetal in forum AWT / Java Swing
    Replies: 3
    Last Post: August 23rd, 2011, 05:41 PM
  3. [SOLVED] Battleship GUI Program
    By javapenguin in forum What's Wrong With My Code?
    Replies: 85
    Last Post: June 7th, 2010, 08:59 AM
  4. [SOLVED] Still need help with Battleship GUI.
    By javapenguin in forum What's Wrong With My Code?
    Replies: 0
    Last Post: June 6th, 2010, 05:57 PM
  5. ActionListener Help?
    By Drag01 in forum AWT / Java Swing
    Replies: 1
    Last Post: March 30th, 2010, 08:21 PM