Java programming part 101 Graphics : Java Animation 4 KeyListener

Опубликовано: 08 Июль 2012
на канале: Redemptie
3,423
10

Java Programming tutorial, GUI, Graphical User Interface. this tutorial is teaching. How to use Java KeyListener for animation,Showing you how to use Key Board keys to control the game.

//below BKGround.java class code

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.ImageIcon;
import javax.swing.JPanel;


public class BKGround extends JPanel implements KeyListener{

Image image;
Image image2;
int x1,y1,x2,y2;
int num;
boolean right;
boolean down;

public BKGround(){

x1 = 100;
y1 = 100;
x2 = 200;
y2 = 200;
num = 0;
right = true;
down = true;
}

public void paint(Graphics g){
num = num + 1;
ImageIcon I = new ImageIcon("image/Abstract-background-1.png");
image = I.getImage();
ImageIcon I2 = new ImageIcon("image/charcustomsheet.gif");
image2 = I2.getImage();
/* if(right == true){
x1 = x1 + 1;
x2 = x2 + 1;
if(x2 == 450){
right = false;
}
}
if(right == false){
x1 = x1 - 1;
x2 = x2 - 1;
if(x1 == 0){
right = true;
}
}

if(down == true){
y1 = y1 + 1;
y2 = y2 + 1;
if(y2 == 350){
down = false;
}
}
if(down == false){
y1 = y1 - 1;
y2 = y2 - 1;
if(y1 == 0){
down = true;
}
}
*/

g.drawImage(image, 0, 0, null);
g.drawImage(image2, x1, y1, x2, y2, 40, 60, 80, 120, null);
repaint();
}

@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_UP){
y1 = y1 - 1;
y2 = y2 - 1;
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
y1 = y1 + 1;
y2 = y2 + 1;
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x1 = x1 + 1;
x2 = x2 + 1;
}
if(e.getKeyCode()==KeyEvent.VK_LEFT){
x1 = x1 - 1;
x2 = x2 - 1;
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}
}

//GraphicsTut.java class below


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.*;


public class GraphicsTut extends JFrame{
Image image;
Image image2;
int x1,y1,x2,y2;
BKGround bkg = new BKGround();


public GraphicsTut(){
this.setTitle("Remember g for Graphics");
this.setSize(450,350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(bkg);
this.addKeyListener(bkg);

}

public static void main(String[] args){
new GraphicsTut();

}

}


На этой странице сайта вы можете посмотреть видео онлайн Java programming part 101 Graphics : Java Animation 4 KeyListener длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь Redemptie 08 Июль 2012, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 3,423 раз и оно понравилось 10 зрителям. Приятного просмотра!