-2

i am trying to make a minesweeper game so far i went to made the layout,my problem is that when i click on a block a java.lang.ArrayIndexOutOfBoundsException: 9 exception occurs here is the code :

import javax.swing.BorderFactory;
import javax.swing.JToggleButton;
import java.awt.*;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.plaf.basic.BasicTabbedPaneUI.MouseHandler;


public final class minesweeper extends javax.swing.JFrame implements          ActionListener, ContainerListener{


public minesweeper() {
    initComponents();
    setLayout(blockr,blockc,fw,fh);

}


@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    panel = new javax.swing.JPanel();
    jMenuBar1 = new javax.swing.JMenuBar();
    NewGame = new javax.swing.JMenu();
    jMenu3 = new javax.swing.JMenu();
    EasyM = new javax.swing.JMenuItem();
    MediumM = new javax.swing.JMenuItem();
    HardM = new javax.swing.JMenuItem();
    Exit = new javax.swing.JMenuItem();

    jLabel1.setText("jLabel1");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setMinimumSize(new java.awt.Dimension(200, 200));
    setPreferredSize(new java.awt.Dimension(200, 200));
    setSize(new java.awt.Dimension(200, 200));

    panel.setPreferredSize(new java.awt.Dimension(200, 300));
    panel.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            panelMouseClicked(evt);
        }
    });
    panel.setLayout(new java.awt.GridLayout(blockr, blockc));

    NewGame.setText("File");

    jMenu3.setText("New Game");

    EasyM.setText("Easy (10mines,9x9blocks)");
    EasyM.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            EasyMActionPerformed(evt);
        }
    });
    jMenu3.add(EasyM);

    MediumM.setText("medium (40mines,16x16blocks)");
    MediumM.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            MediumMActionPerformed(evt);
        }
    });
    jMenu3.add(MediumM);

    HardM.setText("hard(99mines,16x30blocks)");
    HardM.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            HardMActionPerformed(evt);
        }
    });
    jMenu3.add(HardM);

    NewGame.add(jMenu3);

    Exit.setText("Exit");
    Exit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            ExitActionPerformed(evt);
        }
    });
    NewGame.add(Exit);

    jMenuBar1.add(NewGame);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new   javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        


class MouseListener extends MouseAdapter{ 

    public void mouseClicked(MouseEvent me){
        int i=0,j=0;
        for(i=0;i<blockr;i++){
            for(j=0;j<blockc;j++){
                if(me.getSource()==blocks[i][j]){
                    found=true;
                    break;
                }
                if(found)break;
            } 
        }
        if(firstclick){
            spawn(i,j);
            firstclick=false;
        }
       blocks[i][j].setSelected(true);
    }
  }
   public void check(int i,int j){

}
public void checkbomb(int x,int y){
    if(blockValue[x][y]==-1){
        JOptionPane.showMessageDialog(null, "Game Over");
    }


}
public void spawn(int x,int y){
    int r,c;
    for(int k=0;k<bombs;k++){
        do{
        r = ranr.nextInt(blockr);
        c = ranc.nextInt(blockc);
        }while(blockValue[r][c]==-1||(r==x&&c==y));
        blockValue[r][c]=-1;
    }
}
void setLayout(int blockRow,int blockColumm,int fw,int fh){

    firstclick=true;
    blocks=new JToggleButton[blockRow][blockColumm];
    blockValue=new int[blockRow][blockColumm];
    setSize(fw, fh);
    setResizable(false);
    p = this.getLocation();
    mh=new MouseListener();
    getContentPane().removeAll();
    panel.removeAll();

    panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10), BorderFactory.createLoweredBevelBorder()));
    panel.setPreferredSize(new Dimension(fw, fh));
    panel.setLayout(new java.awt.GridLayout(blockRow, blockColumm));
    for(int i = 0; i < blockRow; i++){
        for(int j = 0; j < blockColumm; j++){
            blocks[i][j] = new JToggleButton("");
            blocks[i][j].setSize(25,25);
            blocks[i][j].addMouseListener(mh);
            panel.add(blocks[i][j]);           
        }
    }
    panel.revalidate();
    panel.repaint();

    getContentPane().setLayout(new BorderLayout());
    getContentPane().repaint();
    getContentPane().add(panel, BorderLayout.CENTER);
    setVisible(true);
}

private void EasyMActionPerformed(java.awt.event.ActionEvent evt) {                                      
    fw = 300;
    fh = 350;
    blockr = 9;
    blockc = 9;
    bombs = 10;
    setLayout(blockr,blockc,fw,fh);

}                                     

private void MediumMActionPerformed(java.awt.event.ActionEvent evt) {                                        
   bombs=40;
   fw = 320;
   fh = 320;
   blockr = 16;
   blockc = 16;
   bombs = 40;
   setLayout(blockr,blockc,fw,fh);
}                                       

private void HardMActionPerformed(java.awt.event.ActionEvent evt) {                                      
   bombs=99;
   fw = 600;
   fh = 320;
   blockr = 16;
   blockc = 30;
   bombs= 99;
   setLayout(blockr,blockc,fw,fh);
}                                     

private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                     
    System.exit(0);
}                                    

private void panelMouseClicked(java.awt.event.MouseEvent evt) {                                   
    // TODO add your handling code here:
}                                  


public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
        new minesweeper().setVisible(true);
    });
}
static int blockr=9, blockc=9, fw=300,fh=350,bombs=10;
Point p;
JToggleButton[][] blocks;
int[][] blockValue;
boolean firstclick=true,found;
Random ranc=new Random();
Random ranr=new Random();
MouseListener mh;
// Variables declaration - do not modify                     
private javax.swing.JMenuItem EasyM;
private javax.swing.JMenuItem Exit;
private javax.swing.JMenuItem HardM;
private javax.swing.JMenuItem MediumM;
private javax.swing.JMenu NewGame;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel panel;
// End of variables declaration                   

@Override
public void actionPerformed(ActionEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void componentAdded(ContainerEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void componentRemoved(ContainerEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To   change body of generated methods, choose Tools | Templates.
}
}

the Excpeption as well :

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 9
at minesweeper$MouseListener.mouseClicked(minesweeper.java:132)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6536)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at   java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 7 seconds)

what i suspect is when i try to call the method blocks[i][j].setSelected(true); creates the exception but i dont understand why or what to do to fix it

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Variable names should NOT start with an upper case character. Some of your names are correct, others are not. Be consistent!!! Also, class names SHOULD start with an upper case character. Can you show me a class in the API that doesn't start with an upper case character? – camickr Dec 10 '16 at 17:06

1 Answers1

1

java.lang.ArrayIndexOutOfBoundsException: 9

blockr = 9;
blockc = 9;

Looks to me like you are trying to create a 9x9 grid.

Java indexes are 0 based so your loops should be 0 - 8.

If you are trying to use an index of 9, your looping code is incorrect.

Find the incorrect loop and fix the code.

camickr
  • 321,443
  • 19
  • 166
  • 288