Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package projekt2;
- import java.awt.*;
- import javax.swing.JPanel;
- import java.awt.event.*;
- import javax.swing.*;
- import java.awt.Graphics;
- public class MovingBar extends JFrame implements KeyListener{
- private int recx;
- private int recy;
- private int recw;
- private int rech;
- private int frameWidth = 400;
- private int frameHeight = 300;
- private boolean movingL;
- private boolean movingR;
- JPanel mp = new JPanel();
- public MovingBar()
- {
- this.setTitle("SpaceSpace");
- this.setSize(frameWidth,frameHeight);
- this.recw = 100;
- this.rech = 10;
- this.recx = getWidth() / 2 - this.rech / 2;
- this.recy = getHeight() - this.rech - 10;
- this.getContentPane().setLayout(new BorderLayout());
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- mp.addKeyListener(this);
- this.add(mp);
- mp.setFocusable(true);
- mp.setBackground(Color.BLACK);
- this.movingL = false;
- this.movingR = false;
- }
- @Override
- public void paint(Graphics g)
- {
- super.paint(g);
- g.setColor(Color.WHITE);
- g.fillRect(this.recx, this.recy, this.recw, this.rech);
- repaint();
- }
- public void moveLeft()
- {
- if (this.recx >= 0)
- this.recx--;
- }
- public void moveRight()
- {
- if (this.recx < this.frameWidth - this.recw)
- this.recx++;
- }
- @Override
- public void keyPressed (KeyEvent e)
- {
- if (e.getKeyCode() == KeyEvent.VK_LEFT)
- {
- this.movingL = true;
- this.movingR = false;
- }
- if (e.getKeyCode() == KeyEvent.VK_RIGHT)
- {
- this.movingR = true;
- this.movingL = false;
- }
- }
- @Override
- public void keyReleased (KeyEvent e)
- {
- if (e.getKeyCode() == KeyEvent.VK_LEFT)
- this.movingL = false;
- if (e.getKeyCode() == KeyEvent.VK_RIGHT)
- this.movingR = false;
- }
- @Override
- public void keyTyped(KeyEvent e)
- {
- }
- public void actionHandler()
- {
- if (this.movingL == true )
- moveLeft();
- if (this.movingR == true)
- moveRight();
- }
- }
- //Main
- package projekt2;
- import java.awt.Color;
- public class Main {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- MovingBar mb = new MovingBar();
- mb.setResizable(false);
- mb.setVisible(true);
- mb.actionHandler();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement