- let your frame implement the MouseListener interface
- implement all abstract methods, but in your case it is probably the mouseClicked event
- identify if the button clicked is a left click, using the SwingUtilities class
if it is a left click, then set the x and y, which is the location of your click relative to the frame, not the screen.
public class MouseListeningObject extends JFrame implements MouseListener {
int x, y;
public MouseListeningObject () { addMouseListener(this); }
@Override public void mouseClicked(MouseEvent e) { if(SwingUtilities.isLeftMouseButton(e)){ x = e.getX(); y = e.getY(); } }
@Override public void mousePressed(MouseEvent e) { // Some codes here }
@Override public void mouseReleased(MouseEvent e) { // Some codes here }
@Override public void mouseEntered(MouseEvent e) { // Some codes here }
@Override public void mouseExited(MouseEvent e) { // Some codes here } }
How to set up mouse and keyboard input
Pergunta
Hi I'm trying to program a game using java. This is my first time using java, I am used to C#. In C# I would call Mouse.getLocation() and create a rect using the mouses location. Then by using if(Mouse.Left().toString() == "Pressed") I would then check if the mouse rect intersected with any other objects and act accordingly.
I've noticed in java you aren't provided with methods like these. So I was wondering, is the best way to approach mouse input simply to add listeners on all my clickable objects? I understand listeners and have a good idea how to use them but I was just wanting to check if there are more efficient ways to handle input or ways geared more towards what I'm most conformable with.
Solução
Outras dicas
You want your frame to implement MouseListener then add it in the constructor.
class MyFrame extends JFrame implements MouseListener {
MyFrame() {
addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}