Hello,
First it's best to mention I'm not the best at programming, and quite new to Java.
I was wondering if there is a way to add a listener for particular mouse event(for example mouseEntered) without having to override all of the methods in MouseListener.
In order to practice event listeners, I made a quick program with 3 panels, north,south and center. When a panel is highlighted the background is changed to a certain colour (e.g. south turns red, mid turns yellow).
Here is the code I've used..
final JPanel south = new JPanel();
south.addMouseListener(new MouseListener()
{
public void mouseExited(MouseEvent e)
{
south.setBackground(getBackground());
}
public void mouseEntered(MouseEvent e)
{
south.setBackground(Color.RED);
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
});
I assume theres a better way to do this sort of thing.
Regards,
Kyle
mouseEntered listener
Started by johnsonk, Dec 07 2009 11:40 AM
4 replies to this topic
#1
Posted 07 December 2009 - 11:40 AM
|
|
|
#2
Posted 07 December 2009 - 12:01 PM
They are abstract, as an interface. See below for the right answer.
final JPanel south = new JPanel();
south.addMouseListener(new MouseListener()
{
public void mouseEntered(MouseEvent e)
{
south.setBackground(Color.RED);
}
});
That should work fine, though I haven't tested it.
Edited by ZekeDragon, 07 December 2009 - 12:26 PM.
Fix
Wow I changed my sig!
#3
Posted 07 December 2009 - 12:12 PM
Thanks for your reply,
yeah thats why I tried to do at first. It says I need to override the other methods such as mouseExited, meaning that they are abstract methods of MouseListener or MouseEvent.
Regards,
Kyle
yeah thats why I tried to do at first. It says I need to override the other methods such as mouseExited, meaning that they are abstract methods of MouseListener or MouseEvent.
Regards,
Kyle
Edited by johnsonk, 07 December 2009 - 12:15 PM.
wasn't sure which
#4
Posted 07 December 2009 - 12:17 PM
Misread it, MouseListener is an interface. It has to be abstract. XD
Try changing it to MouseAdapter:
Try changing it to MouseAdapter:
final JPanel south = new JPanel();
south.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent e)
{
south.setBackground(Color.RED);
}
});
Wow I changed my sig!
#5
Posted 07 December 2009 - 12:23 PM
thanks that works perfectly, that's very useful to know!
In all fairness I should have looked at the API, my answer was literally on the first paragraph haha XD.
Regards,
Kyle
In all fairness I should have looked at the API, my answer was literally on the first paragraph haha XD.
Regards,
Kyle


Sign In
Create Account


Back to top









