Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- public class Main {
- public static final int WIDTH = 500;
- public static final int HEIGHT = 500;
- public static void main(String[] args) {
- JFrame frame = new JFrame();
- frame.add(new GameFrame());
- frame.setVisible(true);
- frame.setSize(WIDTH, HEIGHT);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setLocationRelativeTo(null);
- }
- }
- package ru.azad.mygame;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class GameFrame extends JComponent implements Runnable {
- int x = Main.WIDTH / 2;
- int y = Main.HEIGHT / 2;
- public GameFrame() {
- setLayout(new FlowLayout());
- this.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- keyPressed2(e);
- }
- });
- Thread t = new Thread(this);
- t.start();
- }
- public void paintComponent(Graphics g) {
- g.setColor(new Color(0, 0, 0));
- g.fillRect(x, y, 10, 25);
- }
- public void keyPressed2(KeyEvent e) {
- if (e.getKeyCode() == KeyEvent.VK_UP) {
- y++;
- }
- if (e.getKeyCode() == KeyEvent.VK_DOWN) {
- y--;
- }
- if (e.getKeyCode() == KeyEvent.VK_LEFT) {
- x--;
- }
- if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
- x++;
- }
- repaint();
- }
- @Override
- public void run() {
- try {
- while (true) {
- repaint();
- Thread.sleep(20);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment