Jump to content

mouseEntered listener

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
johnsonk

johnsonk

    Newbie

  • Members
  • PipPip
  • 17 posts
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

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
They are not abstract methods, you do not have to define them!
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
johnsonk

johnsonk

    Newbie

  • Members
  • PipPip
  • 17 posts
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

Edited by johnsonk, 07 December 2009 - 12:15 PM.
wasn't sure which


#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Misread it, MouseListener is an interface. It has to be abstract. XD

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
johnsonk

johnsonk

    Newbie

  • Members
  • PipPip
  • 17 posts
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