Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* REMEMBER, IF YOU WANT THE IMAGE TO APPEAR YOU MUST PUT THE PICTURE INSIDE OF ECLIPSE WHICH MEANS YOU DRAG
- THE IMAGE INTO THE SRC OF THE ECLIPSE. */
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class Sam extends JApplet implements MouseMotionListener, MouseListener, KeyListener
- {
- int xPos = 0;
- int yPos = 0; // Position of Icon
- int width, height; // Dimensions of Icon
- Image pic;
- int xDis = 0;
- int yDis = 0; // Displacement of Icon while dragged
- int mousex = 0;
- int mousey = 0;
- int x = 5;
- int y = 5;
- Point mousePosition;
- public void init()
- {
- width = 1500; // Where the width is from where you can drag the image
- height = 1500; // Where the height is from where you can drag the image
- setContentPane(new DrawingPanel());
- addMouseMotionListener(this);
- addMouseListener(this);
- addKeyListener(this);
- setFocusable(true);
- setSize(900, 900);
- pic = getImage(getDocumentBase(), "images.jpg");
- }
- public void mouseMoved(MouseEvent e){}
- public void mousePressed(MouseEvent e)
- {
- mousePosition = e.getPoint();
- mousex = (int)mousePosition.getX();
- mousey = (int)mousePosition.getY();
- System.out.println(mousex);
- System.out.println(mousey);
- }
- public void mouseDragged(MouseEvent e)
- {
- if(mousex > xPos
- && mousex < xPos + width
- && mousey > yPos
- && mousey < yPos + height)
- {
- xDis = e.getX()-mousex;
- yDis = e.getY()-mousey;
- xPos = xPos + xDis;
- yPos = yPos + yDis;
- repaint();
- }
- mousePosition = e.getPoint();
- mousex = (int)mousePosition.getX();
- mousey = (int)mousePosition.getY();
- }
- public void mouseClicked(MouseEvent e){}
- public void mouseReleased(MouseEvent e){}
- public void mouseEntered (MouseEvent e){}
- public void mouseExited (MouseEvent e){}
- public void keyTyped(KeyEvent e){}
- public void keyPressed(KeyEvent e)
- {
- if (e.getKeyCode() == KeyEvent.VK_UP)
- {
- if(yPos != 0) // Wall Barriers
- {
- yPos = yPos - y;
- repaint();
- }
- }
- if (e.getKeyCode() == KeyEvent.VK_DOWN)
- {
- if(yPos != 100) // Wall Barriers
- {
- yPos = yPos + y;
- repaint();
- }
- }
- if (e.getKeyCode() == KeyEvent.VK_LEFT)
- {
- if(xPos != 0) // Wall Barriers
- {
- xPos = xPos - x;
- repaint();
- }
- }
- if (e.getKeyCode() == KeyEvent.VK_RIGHT)
- {
- if(xPos != 100) // Wall Barriers
- {
- xPos = xPos + x;
- repaint();
- }
- }
- }
- public void keyReleased(KeyEvent e){}
- @SuppressWarnings("serial")
- public class DrawingPanel extends JPanel
- {
- public void paintComponent(Graphics g)
- {
- super.paintComponent(g);
- g.drawImage(pic, xPos, yPos,this);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment