Advertisement
heavenriver

FifteenEvent.java

Apr 10th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. package fifteen;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. /**
  6.  * @author SilverKitsune
  7.  */
  8. public class FifteenEvent implements ActionListener
  9.    
  10.     {
  11.     /**
  12.      * Moves the button clicked, where possible.
  13.      */
  14.     public void actionPerformed(ActionEvent ae)
  15.         {
  16.         JButton b = (JButton)ae.getSource();
  17.         int x = b.getX();
  18.         int y = b.getY();
  19.         int dx = (int)b.getMaximumSize().getWidth();
  20.         int dy = (int)b.getMaximumSize().getHeight();
  21.         if(x + dx <= 4 * dx && checkFree(b, x + dx, y))
  22.             b.setLocation(x + dx, y);
  23.         else if(x - dx >= 0 && checkFree(b, x - dx, y))
  24.             b.setLocation(x - dx, y);
  25.         else if(y + dy <= 4 * dy && checkFree(b, x, y + dy))
  26.             b.setLocation(x, y + dy);
  27.         else if(y - dy >= 0 && checkFree(b, x, y - dy))
  28.             b.setLocation(x, y - dy);
  29.         else;
  30.         }
  31.    
  32.     /**
  33.      * Checks if the button can be moved.
  34.      * @param b The button to move.
  35.      * @param x The new X coordinate of the button.
  36.      * @param y The new Y coordinate of the button.
  37.      * @return True if the button can be moved, false otherwise.
  38.      */
  39.     private boolean checkFree(JButton b, int x, int y)
  40.         {
  41.         return b.getParent().getComponentAt(x, y) != FifteenFrame.one &&
  42.                 b.getParent().getComponentAt(x, y) != FifteenFrame.two &&
  43.                 b.getParent().getComponentAt(x, y) != FifteenFrame.three &&
  44.                 b.getParent().getComponentAt(x, y) != FifteenFrame.four &&
  45.                 b.getParent().getComponentAt(x, y) != FifteenFrame.five &&
  46.                 b.getParent().getComponentAt(x, y) != FifteenFrame.six &&
  47.                 b.getParent().getComponentAt(x, y) != FifteenFrame.seven &&
  48.                 b.getParent().getComponentAt(x, y) != FifteenFrame.eight &&
  49.                 b.getParent().getComponentAt(x, y) != FifteenFrame.nine &&
  50.                 b.getParent().getComponentAt(x, y) != FifteenFrame.ten &&
  51.                 b.getParent().getComponentAt(x, y) != FifteenFrame.eleven &&
  52.                 b.getParent().getComponentAt(x, y) != FifteenFrame.twelve &&
  53.                 b.getParent().getComponentAt(x, y) != FifteenFrame.thirteen &&
  54.                 b.getParent().getComponentAt(x, y) != FifteenFrame.fourteen &&
  55.                 b.getParent().getComponentAt(x, y) != FifteenFrame.fifteen;
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement