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);
}
}
vtcompsci - 24 Feb 2006 02:09 GMT
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?
vtcompsci - 24 Feb 2006 02:11 GMT
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?
vtcompsci - 24 Feb 2006 10:06 GMT