Move control as you move your mouse - Java Swing

Java examples for Swing:Mouse Event

Description

Move control as you move your mouse

Demo Code

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame implements ActionListener {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(420, 220);/*from ww  w.  ja va  2  s .co  m*/
    BorderLayout border = new BorderLayout();
    setLayout(border);
    JLabel message = new JLabel("Click OK.");
    add(BorderLayout.NORTH, message);
    MyPanel prank = new MyPanel();
    prank.ok.addActionListener(this);
    add(BorderLayout.CENTER, prank);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent event) {
    System.exit(0);
  }
  public static void main(String[] arguments) {

    new Main();
  }
}

class MyPanel extends JPanel implements MouseMotionListener {
  JButton ok = new JButton("OK");
  int buttonX, buttonY, mouseX, mouseY;
  int width, height;

  MyPanel() {
    super();
    setLayout(null);
    addMouseMotionListener(this);
    buttonX = 110;
    buttonY = 110;
    ok.setBounds(new Rectangle(buttonX, buttonY, 70, 20));
    add(ok);
  }

  public void mouseMoved(MouseEvent event) {
    mouseX = event.getX();
    mouseY = event.getY();
    width = (int) getSize().getWidth();
    height = (int) getSize().getHeight();
    if (Math.abs((mouseX + 35) - buttonX) < 50) {
      buttonX = moveButton(mouseX, buttonX, width);
      repaint();
    }
    if (Math.abs((mouseY + 20) - buttonY) < 50) {
      buttonY = moveButton(mouseY, buttonY, height);
      repaint();
    }
  }

  public void mouseDragged(MouseEvent event) {
  }

  private int moveButton(int mouseAt, int buttonAt, int border) {
    if (buttonAt < mouseAt) {
      buttonAt--;
    } else {
      buttonAt++;
    }
    if (buttonAt > (border - 20)) {
      buttonAt = 5;
    }
    if (buttonAt < 0) {
      buttonAt = border - 80;
    }
    return buttonAt;
  }

  public void paintComponent(Graphics comp) {
    super.paintComponent(comp);
    ok.setBounds(buttonX, buttonY, 70, 20);
  }
}

Related Tutorials