import javax.swing.*; import java.awt.*; import java.awt.event.*; class World extends JComponent implements KeyListener, ActionListener { int count; public void actionPerformed(ActionEvent e) { this.count += 1; System.out.println("Ouch..." + this.count); } public void keyPressed(KeyEvent e) { int value = e.getKeyCode(); System.out.println("Key pressed: " + (char) value); switch (value) { // http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#VK_LEFT case KeyEvent.VK_LEFT : this.current.moveLeft(); this.repaint(); System.out.println("Left arrow pressed."); break; case KeyEvent.VK_RIGHT: this.current.moveRight(); this.repaint(); System.out.println("Right arrow pressed."); break; case KeyEvent.VK_UP : this.current.moveUp(); this.repaint(); System.out.println("Up arrow pressed."); break; case KeyEvent.VK_DOWN : this.current.moveDown(); this.repaint(); System.out.println("Down arrow pressed."); break; case KeyEvent.VK_SPACE: System.out.println("Space bar pressed."); break; default: System.out.println("Unknown key pressed."); break; } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } Shape current; Timer timer; World() { this.timer = new Timer(1000, this); this.current = new TShape(3, 4, this); } void start() { this.timer.start(); } public void paintComponent(Graphics g) { g.drawString("Welcome to Tetris!", 50, 150); this.current.draw(g); System.out.println( current ); } static final int ROWS = 22; static final int COLS = 10; int squareWidth() { return (int) getSize().getWidth() / World.COLS; } int squareHeight() { return (int) getSize().getHeight() / World.ROWS; } }