|
im creating a window that when the mouse moves over one side of it it will turn red and when the mouse ones over the other side it will turn green. im a little confused about the code used to calculate that within my mouseEntered and mouseExited methods.
|
|
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseChanges extends JPanel
{
public void changeBackground(boolean isLeft)
{
Color color = Color.green.darker();
if(isLeft)
color = Color.red;
setBackground(color);
repaint();
}
public static void main(String[] args)
{
MouseChanges mc = new MouseChanges();
mc.addMouseMotionListener(new PanelListener());
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(mc);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class PanelListener extends MouseMotionAdapter
{
int lastSide = -1;
final int LEFT = 0;
final int RIGHT = 1;
public void mouseMoved(MouseEvent e)
{
Point p = e.getPoint();
MouseChanges mc = (MouseChanges)e.getSource();
int middle = mc.getWidth()/2;
int side = p.x <= middle ? LEFT : RIGHT;
if(side != lastSide)
{
mc.changeBackground(p.x <= middle);
lastSide = side;
}
}
}
|
|
|
|
|
|
|
|
|
|