Thread: Project Help
View Single Post
  #2 (permalink)  
Old 02-17-2008, 01:46 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,104
hardwired is on a distinguished road
Code:
import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class KBM{ public static void create (){ JFrame frame = new JFrame("Button Movement"); KeyboardPanel keyboardPanel = new KeyboardPanel(); keyboardPanel.setFocusable(true); frame.add(keyboardPanel); frame.setSize(600, 600); frame.setLocation(100, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String args[]) { new KBM().create(); } } class KeyboardPanel extends JPanel implements KeyListener { int playerLocationX; int playerLocationY; Point lastCell = new Point(); JButton[][] cells = new JButton[7][7]; public KeyboardPanel(){ super(new GridLayout(7, 7)); Random generator = new Random(); playerLocationX = generator.nextInt((6)); // playerLocationX++; // Random generator2 = new Random(); playerLocationY = generator.nextInt((6)); // playerLocationY++; lastCell.setLocation(playerLocationX, playerLocationY); for(int j = 0; j < cells.length; j++){ for(int k = 0; k < cells[0].length; k++) { cells[j][k] = new JButton(); add(cells[j][k]); } } setSelection(); addKeyListener(this); // KeyButtonMovement k = new KeyButtonMovement(); // playerLocationX = k.playerLocationX; // playerLocationY = k.playerLocationY; } public void keyReleased (KeyEvent e){} public void keyTyped (KeyEvent e){} public void keyPressed (KeyEvent e){ switch (e.getKeyCode()){ case KeyEvent.VK_DOWN: if ((playerLocationY +1)!=8){ playerLocationY = playerLocationY +1; System.out.println("DOWN "+playerLocationX+ " "+playerLocationY); } break; case KeyEvent.VK_UP: if ((playerLocationY -1)!=0){ playerLocationY = playerLocationY -1; System.out.println("UP "+playerLocationX+ " "+playerLocationY); } break; case KeyEvent.VK_LEFT: if ((playerLocationX -1)!=0){ playerLocationX = playerLocationX -1; System.out.println("LEFT "+playerLocationX+ " "+playerLocationY); } break; case KeyEvent.VK_RIGHT: if ((playerLocationX +1)!=8){ playerLocationX = playerLocationX +1; System.out.println("RIGHT "+playerLocationX+ " "+playerLocationY); } break; // default: keyChar = e.getKeyChar(); } setSelection(); } private void setSelection() { cells[lastCell.x][lastCell.y].setText(""); cells[lastCell.x][lastCell.y].setBackground( UIManager.getColor("Button.background")); cells[playerLocationX][playerLocationY].setText("P"); cells[playerLocationX][playerLocationY].setBackground(Color.YELLOW); // cells[playerLocationX][playerLocationY].setForeground(Color.BLACK); lastCell.setLocation(playerLocationX, playerLocationY); } }
Reply With Quote