runaway button

V

vtcompsci

does anyone know of a short java program that will make a gui with a
jbutton that will move away from the mosue when it gets near? thanks
 
B

Bart Cremers

package nl.nedcar.transform;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.util.Random;

/**
* @author Bart Cremers
* @since Feb 23, 2006
*/
public class JumpingWindow extends JWindow {
private static final Random RND = new Random();

private static final Rectangle screenRect;

static {
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
GraphicsConfiguration graphConf =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
Insets insets =
Toolkit.getDefaultToolkit().getScreenInsets(graphConf);
screenRect = new Rectangle(insets.left, insets.top,
screenSize.width - insets.right - insets.left,
screenSize.height - insets.bottom -
insets.top);
}

protected void windowInit() {
super.windowInit();

final JButton button = new JButton("Click me to exit!");
add(button);

button.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
Point currentP = button.getLocationOnScreen();
int x;
int y;
do {
x = RND.nextInt(screenRect.width -
button.getWidth()) + screenRect.x;
y = RND.nextInt(screenRect.height -
button.getHeight()) + screenRect.y;
} while (x > currentP.x && x < currentP.x + getWidth()
&& y > currentP.y
&& y < currentP.y + getHeight());

setLocation(x, y);
}
});

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {
JWindow w = new JumpingWindow();
w.pack();
w.setLocationRelativeTo(null);
w.setVisible(true);
}
}
 
V

vtcompsci

hey thanks alot for the program... one question... is there anyway you can
make it so that the jwindow is a jbutton which is inside a jpanel?
 
V

vtcompsci

well i knowticed now that the window isnt a window its a jbutton which is
good but how can you get that inside a jpanel or jframe... and aso with
the random how could you switch that so that it will just move opposite of
the way the mouse moves like in small incriments but evading the mouse?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top