Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // GUI JAVA
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.Timer;
- public class Scale extends JPanel implements ActionListener, KeyListener {
- int ball_x = 100; // X axis inisialization
- int ball_y = 20; // y asix inisialization
- int x2 = 1; //First move trhough X axis
- int y2 = 1; //First move trhough Y axis
- Timer t = new Timer(5, this);
- int x = 0, y = 0, velx = 0, vely = 0;
- public void ballMove(){
- if (ball_x > (300 - 48)) { // 48 is size limit through X
- x2 = -1;
- }
- if (ball_x < 0) {
- x2 = 1;
- }
- if (ball_y > (300 - 65)) { // 65 is size limit through Y
- y2 = -1;
- }
- if (ball_y < 0) {
- y2 = 1;
- }
- ball_x = ball_x + x2; // setting its position to initial X axis
- ball_y = ball_y + y2; // setting its position to initial Y axis
- }
- public Scale() {
- t.start();
- addKeyListener(this);
- setFocusable(true);
- setFocusTraversalKeysEnabled(false);
- }
- public void paintComponent(Graphics s ) {
- super.paintComponent(s);
- s.setColor(Color.BLUE); // Set rectangle colour
- s.fillRect(x, y, 15, 15); // Set rectangle bar size
- //Graphics2D g2d = (Graphics2D) s;
- //g2d.fillOval(ball_x, ball_y, 30, 30);
- //s.setColor(Color.BLACK);
- }
- public void paint(Graphics g) {
- super.paint(g);
- g.setColor(Color.orange);
- Graphics2D g2d = (Graphics2D) g;
- g2d.fillOval(ball_x, ball_y, 30, 30);
- }
- public void actionPerformed(ActionEvent e) {
- if (x < 0) {
- velx = 0;
- x = 0;
- }
- if (x > 270) {
- velx = 0;
- x = 270;
- }
- if (y < 0) {
- vely = 0;
- y = 0;
- }
- if (y > 250) {
- vely = 0;
- y = 250;
- }
- x += velx;
- y += vely;
- repaint();
- }
- public void keyPressed(KeyEvent e) {
- int code = e.getKeyCode();
- if (code == KeyEvent.VK_DOWN) {
- vely = 1;
- velx = 0;
- }
- if (code == KeyEvent.VK_UP) {
- vely = -1;
- velx = 0;
- }
- if (code == KeyEvent.VK_LEFT) {
- vely = 0;
- velx = -1;
- }
- if (code == KeyEvent.VK_RIGHT) {
- vely = 0;
- velx = 1;
- }
- }
- public void keyTyped(KeyEvent e) {
- }
- public void keyReleased(KeyEvent e) {
- velx = 0;
- vely = 0;
- }
- public static void main(String arge[]) throws InterruptedException{
- JFrame f = new JFrame("Scale");
- Scale s = new Scale();
- f.add(s);
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.setSize(300, 300); // Set Main Frame Size.
- f.setVisible(true);
- while (true) {
- s.ballMove();
- s.repaint();
- Thread.sleep(10);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement