Grid Layout - Working Out What Button Is Being Pressed


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: Grid Layout - Working Out What Button Is Being Pressed

Hybrid View

  1. #1
    Join Date
    Mar 2005
    Posts
    12

    Question problem solved

    problem solved - thank you
    Last edited by G_MAN; 03-21-2005 at 01:09 PM.

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Here is a suggestion

    I have not included any adjacent button logic though

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    /**
     * MineSweeper basic layout
     */
    
    public class MineSweeper extends JFrame implements ActionListener {
      BorderLayout borderLayout1 = new BorderLayout();
      MinePanel minePanel = null;
      JPanel jPanel2 = new JPanel();
      JButton closeBtn = new JButton();
      JLabel jLabel1 = new JLabel();
      JTextField rowTF = new JTextField();
      JLabel jLabel2 = new JLabel();
      JTextField colTF = new JTextField();
      JButton restartBtn = new JButton();
    
      /**
       * Constructor
       */
      public MineSweeper() {
        try {
          minePanel=new MinePanel(this);
          jbInit();
          closeBtn.addActionListener(this);
          restartBtn.addActionListener(this);
          addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
            }
          });
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      /**
       * ***************** MAIN *****************
       * @param args
       */
      public static void main(String[] args) {
        MineSweeper msw = new MineSweeper();
        msw.pack();
        msw.setVisible(true);
      }
      /**
       * Get minebutton callbacks, if button is a mine then change
       * color to blue,
       * if not change color to darkGray.
       * Stop listening to it...
       * @param ae
       */
      public void actionPerformed (ActionEvent ae) {
        if (ae.getSource() instanceof MineButton) {
          MineButton aBtn=(MineButton)ae.getSource();
          rowTF.setText(Integer.toString(aBtn.row));
          colTF.setText(Integer.toString(aBtn.col));
          if (aBtn.isMine) {
            aBtn.setBackground(Color.blue);
          } else {
            aBtn.setBackground(Color.darkGray);
          }
          aBtn.removeActionListener(this);
        } else if (ae.getSource()==closeBtn) {
          System.exit(0);
        } else if (ae.getSource()==restartBtn) {
          minePanel.resetButtons();
        }
    
      }
    
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        closeBtn.setText("Close");
        jPanel2.setBorder(BorderFactory.createEtchedBorder());
        jLabel1.setText("Row");
        rowTF.setPreferredSize(new Dimension(40, 22));
        rowTF.setEditable(false);
        rowTF.setText("");
        rowTF.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel2.setText("Column");
        colTF.setPreferredSize(new Dimension(40, 22));
        colTF.setEditable(false);
        colTF.setText("");
        colTF.setHorizontalAlignment(SwingConstants.CENTER);
        restartBtn.setText("Restart");
        this.getContentPane().add(minePanel, BorderLayout.CENTER);
        this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
        jPanel2.add(closeBtn, null);
        jPanel2.add(jLabel1, null);
        jPanel2.add(rowTF, null);
        jPanel2.add(jLabel2, null);
        jPanel2.add(colTF, null);
        jPanel2.add(restartBtn, null);
      }
    }
    /**
     * A mine panel
     */
    class MinePanel extends JPanel  {
      MineButton [][] mineButtons=new MineButton [10][10];
      MineSweeper mineSweeper=null;
    
      // random number part
      private static Random rand=new Random(System.currentTimeMillis());
      private static int getRandom(java.util.Random rand, int min, int max) {
        double d=rand.nextDouble()*(double)max;
        return (int)(d+min);
      }
      /**
       * This chance for this to return true is appr. 33%
       * @return true appr. 33% of the times it is called
       */
      private static boolean getIsMine() {
        int r=getRandom(rand, 0, 100);
        return r<33;
      }
      // end of random number part
    
      /**
       * Constructor
       * @param mineSweeper
       */
      public MinePanel(MineSweeper mineSweeper) {
        this.mineSweeper=mineSweeper;
        setLayout(new GridLayout(10,10,2,2));
        setBackground(Color.darkGray);
        /**
         * Create, add and start listening to buttons
         */
        for (int i=0;i<10;i++) {
          for (int j=0;j<10;j++) {
            boolean isMine=getIsMine();
            mineButtons[i][j]=new MineButton(i,j, isMine);
            mineButtons[i][j].setBackground(Color.lightGray);
            add(mineButtons[i][j],null);
            mineButtons[i][j].addActionListener(mineSweeper);
          }
        }
      }
      public void resetButtons() {
        for (int i=0;i<10;i++) {
          for (int j=0;j<10;j++) {
            boolean isMine=getIsMine();
            mineButtons[i][j].removeActionListener(mineSweeper);
            mineButtons[i][j].setBackground(Color.lightGray);
            mineButtons[i][j].setIsMine(isMine);
            mineButtons[i][j].addActionListener(mineSweeper);
          }
        }
    
      }
    }
    /**
     * A mine button
     */
    class MineButton extends JButton {
      public int row;
      public int col;
      public boolean isMine=false;
      private Dimension btnDim=new Dimension(50,50);
      public MineButton(int row, int col, boolean isMine) {
        super ("O");
        this.row=row;
        this.col=col;
        this.isMine=isMine;
        setHorizontalAlignment(SwingConstants.CENTER);
      }
      public void setIsMine(boolean isMine) {
        this.isMine=isMine;
      }
      /**
       * Ensure proper button size
       * @return
       */
      public Dimension getPreferredSize() {
        return btnDim;
      }
    }
    eschew obfuscation

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    does using the random numbers how you have done it ensure there are no duplicates?
    I am using the random number generator to select which buttons are to be
    mines, nothing else. The buttons are all instances of the MineButton class,
    with individual values for row and column, and some being mines. The
    MineButton class has methods for checking the row/column, and the
    'isMine' boolean value is public.

    what System.out.println can i use in yours and/or mine to see which button is being pressed on the grid? is this possible?
    Of course, if you had run my example you would see that the row and column
    values are displayed at the bottom of the application frame. The modified
    version I deliver here also spits out a text string on System.out when a
    button is clicked.

    i need to limit the number of goes to 10, if more than 10 person loses. if user finds all mines they win, need to say winner or something.
    Seriously ? you give the player 10 goes to pick 5 correct out of 100... ? The
    statistics appear to me like lotto

    Anyway I have set it up so a 'go' is a miss, and a hit is not counted.

    Could what you have done be done by only using one class?
    Certainly, but I am doing object oriented programming, and a one-class
    solution for this would be a real ugly mess, beleive me, and I am not
    going to show you how, that would be cybernetic heresy .

    You see, what you have chosen to do is not exactly a piece of cake...

    Anyway, here is my modification, read carefully....

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    /**
     * MineSweeper basic layout
     */
    
    public class MineSweeper extends JFrame implements ActionListener {
      // set these 4 static values to control the game
      // just remember that ROWS*COLS must exceed NOF_MINES 
      public final static int ROWS = 10;
      public final static int COLS = 10;
      public final static int GOES = 10;
      public final static int NOF_MINES = 5;
      BorderLayout borderLayout1 = new BorderLayout();
      MinePanel minePanel = null;
      JPanel jPanel2 = new JPanel();
      JButton closeBtn = new JButton();
      JLabel jLabel1 = new JLabel();
      JTextField rowTF = new JTextField();
      JLabel jLabel2 = new JLabel();
      JTextField colTF = new JTextField();
      JButton restartBtn = new JButton();
      int nOfGoes=0;
      int hits=0;
      /**
       * Constructor
       */
      public MineSweeper() {
        try {
          minePanel=new MinePanel(this);
          jbInit();
          closeBtn.addActionListener(this);
          restartBtn.addActionListener(this);
          addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
            }
          });
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      /**
       * ***************** MAIN *****************
       * @param args
       */
      public static void main(String[] args) {
        MineSweeper msw = new MineSweeper();
        msw.pack();
        msw.setVisible(true);
      }
      /**
       * Get minebutton callbacks, if button is a mine then change
       * color to blue,
       * if not change color to darkGray.
       * Stop listening to it...
       * @param ae
       */
      public void actionPerformed (ActionEvent ae) {
        if (ae.getSource() instanceof MineButton) {
          System.out.println(ae.getSource());
          if (nOfGoes == GOES) return;
          MineButton aBtn=(MineButton)ae.getSource();
          rowTF.setText(Integer.toString(aBtn.row));
          colTF.setText(Integer.toString(aBtn.col));
          if (aBtn.isMine) {
            aBtn.setBackground(Color.blue);
            hits++;
            if (hits==NOF_MINES) {
              JOptionPane.showMessageDialog(this,"You WIN","WOW",
                                            JOptionPane.INFORMATION_MESSAGE);
            }
          } else {
            aBtn.setBackground(Color.darkGray);
            nOfGoes++;
            if (nOfGoes == GOES) {
              JOptionPane.showMessageDialog(this,"You failed","HHAHAHAHA!!!",
                                            JOptionPane.ERROR_MESSAGE);
            }
          }
          aBtn.removeActionListener(this);
        } else if (ae.getSource()==closeBtn) {
          System.exit(0);
        } else if (ae.getSource()==restartBtn) {
          minePanel.resetButtons();
          nOfGoes=0;
          hits=0;
        }
    
      }
      /**
       * Set up GUI
       * @throws Exception
       */
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        closeBtn.setText("Close");
        jPanel2.setBorder(BorderFactory.createEtchedBorder());
        jLabel1.setText("Row");
        rowTF.setPreferredSize(new Dimension(40, 22));
        rowTF.setEditable(false);
        rowTF.setText("");
        rowTF.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel2.setText("Column");
        colTF.setPreferredSize(new Dimension(40, 22));
        colTF.setEditable(false);
        colTF.setText("");
        colTF.setHorizontalAlignment(SwingConstants.CENTER);
        restartBtn.setText("Restart");
        this.getContentPane().add(minePanel, BorderLayout.CENTER);
        this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
        jPanel2.add(closeBtn, null);
        jPanel2.add(jLabel1, null);
        jPanel2.add(rowTF, null);
        jPanel2.add(jLabel2, null);
        jPanel2.add(colTF, null);
        jPanel2.add(restartBtn, null);
      }
    }
    /**
     * A mine panel
     */
    class MinePanel extends JPanel  {
      MineButton [][] mineButtons=new MineButton [MineSweeper.ROWS][MineSweeper.COLS];
      MineSweeper mineSweeper=null;
    
      // random number part
      private static Random rand=new Random(System.currentTimeMillis());
      private static int getRandom(java.util.Random rand, int min, int max) {
        double d=rand.nextDouble()*(double)max;
        return (int)(d+min);
      }
      /**
       * This chance for this to return true is appr. 5%
       * @return true appr. 5% of the times it is called
       */
      private static boolean getIsMine() {
        int r=getRandom(rand, 0, MineSweeper.ROWS*MineSweeper.COLS);
        return r<=MineSweeper.NOF_MINES;
      }
      // end of random number part
    
      /**
       * Constructor
       * @param mineSweeper
       */
      public MinePanel(MineSweeper mineSweeper) {
        this.mineSweeper=mineSweeper;
        setLayout(new GridLayout(MineSweeper.ROWS,MineSweeper.COLS,2,2));
        setBackground(Color.darkGray);
        /**
         * Create, add and start listening to buttons
         */
        for (int i=0;i<MineSweeper.ROWS;i++) {
          for (int j=0;j<MineSweeper.COLS;j++) {
            mineButtons[i][j]=new MineButton(i,j);
            mineButtons[i][j].setBackground(Color.lightGray);
            add(mineButtons[i][j],null);
            mineButtons[i][j].addActionListener(mineSweeper);
          }
        }
        distributeMines();
      }
      public void resetButtons() {
        for (int i=0;i<MineSweeper.ROWS;i++) {
          for (int j=0;j<MineSweeper.COLS;j++) {
            mineButtons[i][j].setIsMine(false);
            mineButtons[i][j].removeActionListener(mineSweeper);
            mineButtons[i][j].setBackground(Color.lightGray);
            mineButtons[i][j].addActionListener(mineSweeper);
          }
        }
        distributeMines();
      }
      /**
       * This is for getting an even distribution of mines
       */
      public void distributeMines() {
        int mineCount=0;
        while (true) {
          for (int i=0;i<MineSweeper.ROWS;i++) {
            for (int j = 0; j < MineSweeper.COLS; j++) {
              boolean isMine=getIsMine();
              mineButtons[i][j].setIsMine(isMine);
              if (countMines()==MineSweeper.NOF_MINES) return;
            }
          }
        }
      }
      public int countMines() {
        int cnt=0;
        for (int i=0;i<MineSweeper.ROWS;i++) {
          for (int j = 0; j < MineSweeper.COLS; j++) {
            if (mineButtons[i][j].isMine)
              cnt++;
          }
        }
        return cnt;
      }
    }
    /**
     * A mine button
     */
    class MineButton extends JButton {
      public int row;
      public int col;
      public boolean isMine=false;
      private Dimension btnDim=new Dimension(50,50);
      public MineButton(int row, int col) {
        super ("O");
        this.row=row;
        this.col=col;
        setHorizontalAlignment(SwingConstants.CENTER);
      }
      public void setIsMine(boolean isMine) {
        this.isMine=isMine;
      }
      /**
       * Ensure proper button size
       * @return
       */
      public Dimension getPreferredSize() {
        return btnDim;
      }
      public String toString () {
        return "mineButton row: "+row+" column: "+col+" mine: "+isMine;
      }
    }
    Last edited by sjalle; 03-18-2005 at 12:33 PM.
    eschew obfuscation

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Hmm, ok

    Put this method inside the MinePanel.

    Code:
    private void dumpMines() {
      for (int i=0;i<MineSweeper.ROWS;i++) {
          for (int j=0;j<MineSweeper.COLS;j++) {
            System.out.println(mineButtons[i][j]);
          }
      }
    }
    and make a call to it right after each of the two calls to distributeMines().
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center