Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

SudokuGUI

By: valdeEdius on Mar 16th, 2012  |  syntax: Java  |  size: 6.65 KB  |  views: 62  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.  
  2. import java.awt.Dimension;
  3. import java.awt.Font;
  4. import java.awt.Frame;
  5. import java.awt.Color;
  6. import java.awt.BorderLayout;
  7. import java.awt.GridLayout;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.awt.event.KeyListener;
  11. import java.awt.event.WindowEvent;
  12. import java.awt.event.WindowAdapter;
  13. import java.beans.PropertyChangeListener;
  14.  
  15. import javax.swing.BorderFactory;
  16. import javax.swing.JPanel;
  17. import javax.swing.JButton;
  18. import javax.swing.JTextField;
  19. import javax.swing.UIManager;
  20. import javax.swing.event.DocumentEvent;
  21. import javax.swing.event.DocumentListener;
  22.  
  23. public class GUI extends Frame
  24. {
  25.   private static final long serialVersionUID = 1L;
  26.   private JButton newGame;
  27.   private JButton solveGame;
  28.   private JButton checkAnswers;
  29.  
  30.   private JPanel centerPanel;
  31.   private JPanel eastPanel;
  32.   private JPanel gridBlocks;
  33.  
  34.   private int answer;
  35.    
  36.  
  37.  
  38.  
  39.   /**Constructor:
  40.    * This GUI is made of two parts (East/Center) in a border layout.
  41.    * The East portion contains two buttons, centered vertically, of
  42.    * the same width. The Center portion contains the Sudoku game and
  43.    * will scale to the window's size after the preferred width of the
  44.    * East portion is satisfied.
  45.    */
  46.   public GUI(int[][] map, int[][] key)
  47.   {
  48.     setLayout(new BorderLayout());
  49.     setBackground(Color.lightGray);
  50.     UIManager.getLookAndFeel();
  51.     setTitle("Sudoku!");
  52.     setPreferredSize(new Dimension(400, 400));
  53.     add("East",  getEastPanel());
  54.     add("Center", getCenterPanel(map, key));
  55.     pack();
  56.    
  57.    
  58.     //Handles the exit call.
  59.     addWindowListener(new WindowAdapter()
  60.     {
  61.       public void windowClosing(WindowEvent e)
  62.       {
  63.         setVisible(false);
  64.         dispose();
  65.         System.exit(0);
  66.       }
  67.     });
  68.    
  69.     /**Listeners*/
  70.    
  71.     getNGButton().addActionListener(new ActionListener()
  72.     {
  73.       public void actionPerformed(ActionEvent e)
  74.       {
  75.         //TODO Create method to start new game.
  76.       }
  77.     });
  78.     getCAButton().addActionListener(new ActionListener()
  79.     {
  80.       public void actionPerformed(ActionEvent e)
  81.       {
  82.       }
  83.     });
  84.     getSGButton().addActionListener(new ActionListener()
  85.     {
  86.       public void actionPerformed(ActionEvent e)
  87.       {
  88.         //TODO Add Solve Game button.
  89.       }
  90.     });
  91.    
  92.     /**EndListeners*/
  93.   }
  94.   private JPanel getCenterPanel(int[][] map, int[][] key)
  95.   {
  96.     if(centerPanel==null)
  97.     {
  98.       centerPanel = new JPanel(new BorderLayout());
  99.       centerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
  100.       centerPanel.add("Center",getGridBlocks(map, key));
  101.     }
  102.     return centerPanel;
  103.   }
  104.   private JPanel getEastPanel()
  105.   {
  106.     if(eastPanel==null)
  107.     {
  108.       /**
  109.        * 0,1 allows for only 1 column, but any amount
  110.        * of rows. Grid items are always the same size.
  111.       **/
  112.       eastPanel = new JPanel(new GridLayout(0,1));
  113.       eastPanel.add(getNGButton());
  114.       eastPanel.add(getCAButton());
  115.       eastPanel.add(getSGButton());
  116.     }
  117.     return eastPanel;
  118.   }
  119.  
  120.   /**----Buttons----*/
  121.   private JButton getNGButton()
  122.   {
  123.     if (newGame == null)
  124.       newGame = new JButton("New Game");
  125.     return newGame;
  126.   }
  127.   private JButton getCAButton()
  128.   {
  129.     if (checkAnswers == null)
  130.       checkAnswers = new JButton("Check Answers");
  131.     return checkAnswers;
  132.   }
  133.   private JButton getSGButton()
  134.   {
  135.     if (solveGame == null)
  136.       solveGame = new JButton("Solve Game");
  137.     return solveGame;
  138.   }
  139.   /**----EndButtons----*/
  140.  
  141. //  private void checkAnswers(int[][] map)
  142. //  {
  143. //    for(int i=0;i<map.length;i++)
  144. //      
  145. //  }
  146.  
  147.   private JPanel getGridBlocks(int[][] map, int[][] key)
  148.   {
  149.     if(gridBlocks==null)
  150.     {
  151.       gridBlocks = new JPanel(new GridLayout(0,3));
  152.       for(int bBlocks=0;bBlocks<9;bBlocks++)
  153.       {
  154.         /**
  155.          * Generate the inner blocks that will
  156.          * be filled inside the larger grid.
  157.         **/
  158.         JPanel smallBlocks = new JPanel(new GridLayout(0,3));
  159.         smallBlocks.setBorder(BorderFactory.createLoweredBevelBorder());
  160.         Font font = new Font(smallBlocks.getFont().getName(),smallBlocks.getFont().getStyle(),35);
  161.         JTextField[][] cells = new JTextField[9][9];
  162.         for(int sBlocks=0;sBlocks<9;sBlocks++)
  163.         {
  164.           //Some math to determine current position aware of offset.
  165.          int row = sBlocks / 3 + (bBlocks / 3) * 3;
  166.          int col = sBlocks % 3 + (bBlocks % 3) * 3;
  167.          final int ref = map[row][col];
  168.          
  169.          //If the reference == 0, print blank else print the reference.
  170.          cells[row][col] = new JTextField(ref==0?"":Integer.toString(ref));
  171.          final JTextField cell = cells[row][col];
  172.          
  173.          //Lock cells that already have a correct value based on original map.
  174.          if(ref!=0) cell.setEditable(false);
  175.          //No need to create a listener if the cell is locked.
  176.  
  177.  
  178.          /**
  179.           * This will "listen" to each JTextField for a change.
  180.           * Changes will prompt a check, if the check is successful
  181.           * the cell's background will change to green. If the check
  182.           * shows that the number entered is wrong then you get a red
  183.           * background. If the cell becomes blank you get back to white.
  184.          **/
  185.          
  186.          else cell.addActionListener(new ActionListener()
  187.          {
  188.            public void actionPerformed(ActionEvent event)
  189.            {
  190.              answer = ref;
  191.              JTextField cell = (JTextField) event.getSource();
  192.              System.out.print(cell.getText()+" response triggered..."+answer);
  193.              //Trim cells that are >1 length.
  194.              if(cell.getText().length()>1)
  195.              {
  196.                String str = cell.getText();
  197.                str = str.replaceAll("(.)*", "$1");
  198.                System.out.println(cell.getText());
  199.                cell.setText(str);
  200.                System.out.println("Changed to: " + cell.getText());
  201.              }
  202.            }
  203.          });
  204.          
  205.          //Sets the cell's property name for callback later.
  206.          cell.getDocument().getProperty("val");
  207.          cell.setFont(font);
  208.          
  209.          //Assigns the cell to the current 3x3 block.
  210.          smallBlocks.add(cell);
  211.         }
  212.        
  213.         //Assigns all of the the 3x3 blocks to the 9x9 grid.
  214.         gridBlocks.add(smallBlocks);
  215.       }
  216.     }
  217.     return gridBlocks;
  218.   }
  219.  
  220.  
  221.   /** A simple main to let us test the GUI */
  222.   public static void main(java.lang.String[] args)
  223.   {
  224.     int[][] map=new int[9][9];
  225.     int[][] key=new int[9][9];
  226.     (new GUI(map,key)).setVisible(true);
  227.   }
  228. }