import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Rectangle;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
class Canvas extends JPanel
{
//attributes
private Rectangle sampleObject;
//constructor
public Canvas ( )
{
//initialize object
sampleObject = new Rectangle ( 5, 5, 10, 10 );
//set canavs background colour
setBackground ( Color.black );
//add the key listener in the constructor of your canavas/panel
addKeyListener ( new myKeyListener ( ) );
//ensure focus is on this canavas/panel for key operations.
setFocusable ( true );
}
//painting
public void paintComponent ( Graphics graphics )
{
super.paintComponent ( graphics );
Graphics2D graphics2d = ( Graphics2D ) graphics;
graphics.setColor ( Color.red );
graphics2d.fill ( sampleObject );
}
//function which essentially re-creates rectangle with varying x orientations. (x-movement)
public void mutateRectangleXOrientation ( int mutationDistance )
{
sampleObject.setBounds ( ( int ) sampleObject.getX ( ) + mutationDistance, ( int ) sampleObject.getY
( ), ( int ) sampleObject.getWidth ( ), ( int ) sampleObject.getHeight ( ) );
}
//function which essentially re-creates rectangle with varying y orientations. (y-movement)
public void mutateRectangleYOrientation ( int mutationDistance )
{
sampleObject.setBounds ( ( int ) sampleObject.getX ( ), ( int ) sampleObject.getY ( ) +
mutationDistance, ( int ) sampleObject.getWidth ( ), ( int ) sampleObject.getHeight ( ) );
}
//listener
private class myKeyListener implements KeyListener
{
//implement all the possible actions on keys
public void keyPressed ( KeyEvent keyEvent )
{
switch ( keyEvent.getKeyCode ( ) )
{
case KeyEvent.VK_RIGHT:
{
mutateRectangleXOrientation ( 10 );
}
break;
case KeyEvent.VK_LEFT:
{
mutateRectangleXOrientation ( -10 );
}
break;
case KeyEvent.VK_UP:
{
mutateRectangleYOrientation ( -10 );
}
break;
case KeyEvent.VK_DOWN:
{
mutateRectangleYOrientation ( 10 );
}
break;
case KeyEvent.VK_ESCAPE:
{
System.exit ( 0 );
}
break;
}
repaint ( ); //this is here to ensure that the screen updates per graphics operation
}
public void keyReleased ( KeyEvent keyEvent )
{
}
public void keyTyped ( KeyEvent keyEvent )
{
}
}}
public class Display
{
public static void main ( String [ ] arguments )
{
JFrame frame = new JFrame ( "key listener demo" );
Canvas panel = new Canvas ( );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.add ( panel );
frame.setContentPane ( panel );
frame.setPreferredSize ( new Dimension ( 800, 600 ) );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
frame.pack ( );
}
}
No comments:
Post a Comment