Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ballz;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.MouseEvent;
- import java.awt.event.MouseListener;
- import java.awt.event.MouseMotionListener;
- import java.io.File;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- import javax.swing.*;
- public class MyApplication {
- MyFrame frame = new MyFrame();
- public static void main(String[] args) {
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception e) {
- e.printStackTrace();
- }
- new MyApplication();
- }
- }
- class MyFrame extends JFrame {
- MyPanel panel = new MyPanel();
- public MyFrame() {
- this.setTitle("Test Application");
- this.setSize(800, 600);
- this.setLocationRelativeTo(null);
- this.setResizable(false);
- this.getContentPane().add(panel);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setVisible(true);
- }
- }
- class MyPanel extends JPanel implements MouseListener, MouseMotionListener {
- private final int IMAGE_WIDTH = 100;
- private final int IMAGE_HEIGHT = 100;
- private Image ball;
- private int ballX = 0, ballY = 0;
- private int ballXDiff = 0, ballYDiff = 0;
- private Timer tm;
- public MyPanel() {
- try {
- ball = ImageIO.read(new File("src/ballz/ball.png"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- this.addMouseListener(this);
- this.addMouseMotionListener(this);
- tm = new Timer(10, new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- repaint();
- }
- });
- }
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- g.drawImage(ball, ballX, ballY, null);
- }
- @Override
- public void mouseDragged(MouseEvent e) {
- if (getCursor().getType() == Cursor.HAND_CURSOR) {
- ballX = e.getX() - ballXDiff;
- ballY = e.getY() - ballYDiff;
- }
- }
- @Override
- public void mouseMoved(MouseEvent e) {
- if (e.getX() >= ballX && e.getX() <= ballX + 100 && e.getY() >= ballY && e.getY() <= ballY + 100) {
- setCursor(new Cursor(Cursor.HAND_CURSOR));
- } else {
- setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
- }
- }
- @Override
- public void mouseClicked(MouseEvent e) {
- }
- @Override
- public void mouseEntered(MouseEvent e) {
- }
- @Override
- public void mouseExited(MouseEvent e) {
- }
- @Override
- public void mousePressed(MouseEvent e) {
- if (getCursor().getType() == Cursor.HAND_CURSOR) {
- ballXDiff = e.getX() - ballX;
- ballYDiff = e.getY() - ballY;
- tm.start();
- }
- }
- @Override
- public void mouseReleased(MouseEvent e) {
- tm.stop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement