Reputation: 35
I am trying to create a JFrame
that will register MouseEvents
for my game. However, when the following code is run, the console only prints "in" and "out" when you drag the frame border and then move your cursor. Very confusing. I tried adding the component glassPane
and then adding the MouseListener
there but it still is unsuccessful.
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class Window extends JFrame implements MouseListener {
private static final long serialVersionUID = -240840600533728354L;
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setVisible(true);
frame.addMouseListener(this);
game.start();
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("out");
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
}
Upvotes: 1
Views: 425
Reputation: 285440
I think that the last thing that you want to do is to add the MouseListener to the JFrame, since the JFrame shouldn't have this responsibility. It's responsibility should be to hold and display the components that are added to it, and it is likely one of those components, probably the one that displays the game's active view, very likely a JPanel, which should get this MouseListener.
Some side notes:
this
object, so yet another (and stronger) reason not to have this class extend JFrame.getPreferredSize()
method, and then letting the JFrame achieve this by calling pack()
on the JFrame after adding all components to it.Upvotes: 2
Reputation: 168845
Add the MouseListener
to the Game
(that actually needs the mouse events) rather than the JFrame
(which doesn't, and adds a complication with the frame decorations/border).
Upvotes: 2