Showing posts with label mouselistener. Show all posts
Showing posts with label mouselistener. Show all posts

Saturday, 9 June 2012

PingPong Game in Java

Board.java 

 

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener{
 
 private final int width = 600;
 private final int height = 600;
 
 private int delay = 30;//time delay to update
 private int board_x;//board x location
 private int board_y;//board y location
 private int ball_x;//ball x location
 private int ball_y;//ball y location
 private float ball_xv;//ball x violation
 private float ball_yv;//ball y violation
 
 //conditions
 private boolean running = true;
 private boolean contin= true; 
 private boolean tryagain = false;
 
 //for keyboard 
 private boolean pause = false;
 private boolean left = false;
 private boolean right = false;
 
 //for mouse motions
 private boolean dragged = false;
 private int howfarx = 0; //how far mouse click x coordinate from object's x coordinate
 
 
 private Image ball;
 private Image board;
 private Timer timer;
 private Image background;
 
 private String msg = "presss";
 
 
 public Board()
 {
  addKeyListener(new TAdapter()); 
  addMouseMotionListener(new MAdapter());
  addMouseListener(new MAdapter());
  setBackground(Color.white);
  load();
  setFocusable(true);
  init();
 }
 public void load()
 {
  board = new ImageIcon("C:\\javapics\\board.png").getImage();
  ball = new ImageIcon("C:\\javapics\\ae.png").getImage();
  background = new ImageIcon("C:\\javapics\\backgroud.png").getImage();
 }
 public void actionPerformed(ActionEvent e) {
  
  if(running)
  {
      if(contin)
      {
       ballmoving();
       boardmove();
       lose();
      }
      
  }
   repaint();
 }
 public void start()
 {
  ball_xv = -0.4f;
  ball_yv = -0.3f;
  board_x = 240;
  board_y = 580;
  ball_x = 300;
  ball_y = 240;
 }
 public void init()
 {
  start();
  timer = new Timer(delay,this);
  timer.start();
 }
 public void paint(Graphics g)
 {
  super.paint(g);
  if(contin)
  {
   g.drawImage(ball, ball_x, ball_y,this);
   g.drawImage(board, board_x, board_y,this);
   Toolkit.getDefaultToolkit().sync();
   g.dispose();
  }
  if(tryagain)
  {
   String msg2 = "Press Enter to try again";
         Font small = new Font("Arial", Font.BOLD, 15);

         g.setColor(Color.black);
         g.setFont(small);
         g.drawString(msg2,200,300);
         
  }
  if(pause)
  {
   String msg2 = "Pause! Press Space to continue";
         Font small = new Font("Helvetica", Font.BOLD, 15);

         g.setColor(Color.black);
         g.setFont(small);
         g.drawString(msg2,200,300);
         
  }
  if(!running)
  { 
   g.drawImage(background, 0, 0,this);
  }
  
 }
 public void lose()
 {
  if(ball_y + 20 > height)
  { 
   contin = false;
   tryagain = true;
   
  }
  
 }
 public void ballmoving()
 {
  
  if(ball_x < 1)
   ball_xv = Math.abs(ball_xv);
  else if((ball_x + 20) > (width-21))
   ball_xv = -Math.abs(ball_xv);
  
  if(ball_y < 1)
   ball_yv = Math.abs(ball_yv);
  else if((ball_y+20) > (height-21))
   if(ball_x >= board_x && ball_x <= (board_x+100) )
   ball_yv = -Math.abs(ball_yv);
  
  update(delay);
  
 }
 public void update(int timedelay)//to update ball location on the screen
 {
  ball_x = (ball_x + (int)(ball_xv*delay));
  ball_y = (ball_y + (int)(ball_yv*delay));
 }
 public void boardmove()//to play with keyboard
 {
  if(left){
   board_x -= 40;
   left = false;
  }
  if(right){
   board_x += 40;
   right = false;
  }
 }
 private class MAdapter extends MouseAdapter
 {
  public void mousePressed(MouseEvent e)
  {
   int mousex = e.getX();
   int mousey = e.getY();
   if(mousex >= board_x && mousex <= (board_x+ 100))
    if(mousey >= board_y && mousey <= (board_y+100)){
     dragged = true;
     howfarx =  mousex - board_x;
   }else {
     dragged = false;
   }
  }
  public void mouseDragged(MouseEvent e)
  { 
   if(dragged){
    board_x = e.getX() - howfarx;
    
    board_x = Math.max(0, board_x);//to prevent overflow from sides
    board_x = Math.min(board_x, (width-120));/////////////////////
   }
  }
  public void mouseExited(MouseEvent e)
  {
   dragged = false;
   howfarx = 0;
  }
  public void mouseMoved   (MouseEvent e) {}  // ignore these events
  public void mouseEntered (MouseEvent e) {}  // ignore these events
  public void mouseClicked (MouseEvent e) {}  // ignore these events
  public void mouseReleased(MouseEvent e) {}  // ignore these events
 }
 private class TAdapter extends KeyAdapter
 { 
  public void keyPressed(KeyEvent e)
  {
   int key = e.getKeyCode();
   if(key == KeyEvent.VK_Z)
   { 
    msg = "pressed z";
    if((board_x - 40) >= 0)//to prevent overflow from left side from 
     left = true;
    else
     left = false;//nothing
   }
   if(key == KeyEvent.VK_X)
   {
    msg = "pressed x";
    if((board_x + 150) <= width)//to prevent overflow form right side of game area
     right = true;
    else 
     right = false;//nothing
   }
   if(key == KeyEvent.VK_ENTER){
    start();
    contin = true;
    tryagain = false;
    pause = false;
   }
   if(key == KeyEvent.VK_SPACE){
    if(!pause){
    contin = false;
    pause = true;
    tryagain = false;
    }else{
     contin = true;
     pause = false;
     tryagain = false;
    }
   }
   if(key == KeyEvent.VK_ESCAPE){
    running = false;
    contin = false;
    pause = false;
    tryagain = false;
   }
  }
 }
}



import javax.swing.*;
public class pinpong extends JApplet {

 /**
  * @param args
  */
 public pinpong()
 { 
  this.setContentPane(new Board()); 
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  JFrame window = new JFrame();
  window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(586, 630);
        window.setLocationRelativeTo(null);
        window.setTitle("pinpong");
        window.setContentPane(new Board());
        window.setResizable(false);
        window.setVisible(true);
 }

}

Friday, 27 April 2012

Dragging image in java

Draging Image dragme.java

import javax.swing.JFrame;
public class dragme extends JFrame{
 
 public dragme(){
  
  add(new dragged());
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setLocationRelativeTo(null);
        setTitle("Dragging App");

        setResizable(false);
        setVisible(true);
  
 }
 
 public static void main(String[] args){
  new dragme();
 }
 
}


Dragged Image Class dragged.java

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;

import javax.swing.*;

public class dragged extends JPanel implements MouseMotionListener, MouseListener {
 private Image Dragged;
 private Image background;
 private static int x_coord = 150;
 private static int y_coord = 150;
 private boolean isdragged;
 private static int x_dragFrom = 0;
 private static int y_dragFrom = 0;
 public dragged(){
  
  setPreferredSize(new Dimension(300,300));
  setBackground(Color.WHITE);
  this.addMouseMotionListener(this);
  this.addMouseListener(this);
  LoadImage();
  
 }
 
 public void LoadImage(){
  
  Dragged = new ImageIcon("C:\\javapics\\deneme.png").getImage();
  background = new ImageIcon("C:\\javapics\\daaad.png").getImage();
 }
 
 public void paintComponent(Graphics g){
  
  super.paintComponent(g);
  g.drawImage(background, 0, 0, null);
  g.drawImage(Dragged, x_coord, y_coord, this);
  
 }
 public void mousePressed(MouseEvent e) {
        int x = e.getX();   // Save the x coord of the click
        int y = e.getY();   // Save the y coord of the click
        
        if (x >= x_coord && x <= (x_coord + Dragged.getWidth(null))
                && y >= y_coord && y <= (y_coord + Dragged.getWidth(null))) {
            isdragged = true;
            x_dragFrom = x - x_coord;  // how far from left
            y_dragFrom = y - y_coord;  // how far from top
        } else {
            isdragged = false;
        }
    }
  public void mouseDragged(MouseEvent e) {
         if (isdragged) {  
            
             x_coord = e.getX() - x_dragFrom;//to better dragging view
             y_coord = e.getY() - y_dragFrom;//to better dragging view
             
            //to prevent overflow left and right side
             x_coord  = Math.max(x_coord , 0);
             x_coord  = Math.min(x_coord , getWidth() - Dragged.getWidth(null));
             
             //to prevent overflow up and down side
             y_coord  = Math.max(y_coord , 0);
             y_coord  = Math.min(y_coord , getHeight() - Dragged.getHeight(null));
             
             this.repaint(); // Repaint because position changed.
         }
     }

     //we should change isdragged variable when mouse released for dragging
     public void mouseExited(MouseEvent e) {
         isdragged = false;
     }

     public void mouseMoved   (MouseEvent e) {}  // ignore these events
     public void mouseEntered (MouseEvent e) {}  // ignore these events
     public void mouseClicked (MouseEvent e) {}  // ignore these events
     public void mouseReleased(MouseEvent e) {}  // ignore these events
}