Error using mouseClicked method - java

I'm trying to use the mouseClicked class in my program just to test and figure out. The only problem is that every time I use it I get an error telling me that "void" is the wrong type for mouseClicked. Every website and tutorial I've visited shows me that void is the type I should be using. Here's my code:
public static void door1(){
int x = c.getHeight() / 10;
int y = c.getHeight() * 20 / 100;
public void mouseClicked(MouseEvent e) {
c.drawLine("It worked!",y, x);
}
}

You cannot nest methods in Java. Your class must implement MouseListener inorder to use mouseClicked().
You will also need to implement:
void mousePressed(MouseEvent e) // Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e) // Invoked when a mouse button has been released on a component.
void mouseEntered(MouseEvent e) // Invoked when the mouse enters a component.
void mouseExited(MouseEvent e) // Invoked when the mouse exits a component.

Related

Java 2D Game - MouseClicked & MouseMoved methods

Problem
I have two MouseEvent handlers (mouseClicked and mouseMoved), and they both work, but only separately.
If I click the mouse, the action gets processed fine. (bullet gets fired)
If I move the mouse, the action gets processed fine. (the sprite moves)
The problem occurs when I do both actions at the same time (moving mouse whilst clicking). The mouseMoved event goes through fine, but the mouseClicked event doesn't get called.
The below code is in my Game class constructor, which is extending JPanel.
this.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
//This creates a new bullet, and adds to an array to get drawn.
bullet = new Bullet(105, e.getY()+5, bulletTexture);
bulletsOnScreen.add(bullet);
e.consume();
}
});
this.addMouseMotionListener(new MouseAdapter(){
#Override
public void mouseMoved(MouseEvent e){
//This increments the sprites position on the screen.
player.setYPosition(e.getY()-50);
e.consume();
};
});
What I've tried
I have tried using SwingWorker objects to run the mouseMoved in a background thread, but the results are the same (bullet doesn't fire).
#Override
public void mouseMoved(MouseEvent e){
SwingWorker myWorker = new SwingWorker<Void, Void>(){
#Override
protected Void doInBackground() throws Exception {
player.setYPosition(e.getY()-50);
e.consume();
return null;
}
};
myWorker.execute();
};
I have also tried to check for a mouseClick within the mouseMoved method, again to no success.
public void mouseMoved(MouseEvent e){
if(e.getButton() == MouseEvent.MOUSE_CLICKED){
//Create bullet and add to array (but this never gets called)
}
player.setYPosition(e.getY()-50);
e.consume();
};
If anyone has any ideas or pointers, it would be great thanks.
Here's some code I cooked to have full working example of behavior you described.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}
#Override
public void mouseClicked(MouseEvent e) {
System.exit(1);
}
});
frame.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("Moved");
}
});
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 100);
frame.setVisible(true);
}
});
}
}
As you will see when moving around frame you will get lots of "Moved" events.
Most interesting for you will be part that when you press mouse button down you will see "Pressed". If you release without moving there will be clicked event ( app will exit ). Closing app might be a bit extreme but we have to be sure that we don't miss that event.
But when you press down mouse button, hold it and move, you won't see any move event triggered. Then, when you release, you won't get clicked event fired either.
I'm not sure about this part but it looks like mouseClicked will be triggered only if mousePressed and mouseReleased event occur one after another.
In your game, when you click and move your mouse at the same time you basically do
mousePressed -> mouseMoved -> mouseReleased
but this doesn't fire mouseClicked as a result.
My advice on that would be that you handle mousePressed instead of mouseClicked or try to adapt MouseAdapter#mouseDragged method to your needs.

Simulate MousePress to enter MouseDragged

I am trying to achieve:
1. User performs a mouse-press on parent JFrame
2. Child JFrame becomes visible at mouse location
3. While mouse-button remains pressed, the user can drag the child JFrame across the screen by moving the mouse
The problem:
I can mimic a mouse-press but it does not 'grab' the child JFrame--hence the child JFrame is not being dragged unless the user manually clicks the child JFrame again. I want the process to be smooth without any interruptions: i.e. steps 1-3 (above) should all execute with a single mouse-press.
Failed attempts:
1. I have tried using Robot's mousePressed() to simulate an additional mouse-press on the child. This works, however, it's not clean and can be quite buggy--especially if the PC/device is slow or the user moves the mouse too quickly. This is not a good solution.
2. Using the Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new MouseEvent()); results in the exact same issue as depicted by the current code.
3. When adding a KeyListener (for testing) to both the child and the parent, when the mouse-press is made, the child window is focused and responds to the implemented KeyListener--the parent's KeyListener is not activated..
The Code:
final JFrame parent = new JFrame(), child = new JFrame();
parent.setSize(256, 256);
child.setSize(128,128);
parent.setVisible(true);
parent.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
child.setVisible(true);
child.setLocation(e.getXOnScreen()-48, e.getYOnScreen()-48);
int id = MouseEvent.MOUSE_PRESSED;
long time = System.currentTimeMillis();
int x = 48;
int y = 48;
int button = MouseEvent.BUTTON1_MASK;
child.dispatchEvent(new MouseEvent(child, id, time, button, x, y, 1, false));
}
});
child.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
child.setLocation(e.getXOnScreen()-48, e.getYOnScreen()-48);
}
});
child.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed!");
}
});
Even though the child JFrame has the focus, the MousePress remains active on the parent. To resolve the issue in a stable manner, the parent should 'forward' its MouseDragged event to the child as shown below:
parent.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
child.setVisible(true);
child.setLocation(e.getXOnScreen()-48, e.getYOnScreen()-48);
}
});
parent.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
child.dispatchEvent(new MouseEvent(child, e.getID(), e.getWhen(), e.getButton(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger()));
}
});
child.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
child.setLocation(parent.getX()+e.getX()-48, parent.getY()+e.getY()-48);
}
});
Even this is not fully 'clean' because the code is relying on the parent's frame visibility. However, it is a stable solution (unlike Robot).

How to set up mouse and keyboard input

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.
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
}
}
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) {}
}

Java - MousePress Hold and Release event listener

hello is there a way mouse even that can Hold the mouse and release cause I can't find it on google.
so for example this image..
When the jTextBox is **** when he click the button, he see the words oops...
then after he release the click of mouse the jTextBox will back to **** again
I know this code already but the mouseevent is I only don't know
Yes. You will want to implement the MouseListener interface with a new class and add this new Listener against your button with the following;
button.addMouseListener(new YourMouseListener());
An example custom MouseListener might look like this.
class YourMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
// Insert code to show password
}
#Override
public void mouseReleased(MouseEvent e) {
// Insert code to hide password again
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
I hope this helps.
You'll need a Robot object. This can do things as follows:
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
The Mousebutton is pressed until you do this:
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
This should do what you want.

Adding MouseMotionListeners

I currently have an abstract class which extends JComponent. In this class I have defined a method as follows:
public void makeMouseOverListener(){
System.out.println("Inside make mouseover...");
MouseMotionListener ret = new MouseMotionListener(){
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}
};
this.addMouseMotionListener(ret);
}
I extend this abstract class with a few other objects, and in the constructors of each of those objects I call this method. I always see the first println, but the "Mouse Moved" line never shows up in my console. I also tried directly creating this MouseMotionListener in each constructor, but with the same results. So ultimately my question is, How can I ensure that I get a working motion listener into my objects? Thank you in advance!
The code inside of the new MouseMotionListener( code ) it seems like this ..
**
MouseMotionListener ret = new MouseMotionListener(
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}
});
**
If you're invoking makeMouseOverListener in the constructor of your custom components, then its very likely that the mouse position is never positioned over the component itself. Ensure that the dimension of the component is great than 0 x 0. This can be achieved by using a layout manager. e.g. position the component at BorderLayout.CENTER location.

Categories