Java AWT mouse events - java

I have an applet that makes use of the AWT event model. It has a boolean that says if the left button is pressed or not. Here is a sample code:
public class Game extends Applet implements MouseListener
{
boolean isLeftButtonPressed;
public void init()
{
addMouseListener(this);
isLeftButtonPressed = false;
}
public void paint(Graphics g)
{
g.drawString("Is Button Pressed: " + isLeftButtonPressed, 20, 20);
}
#Override
public void mouseClicked(MouseEvent e)
{
isLeftButtonPressed = true;
repaint();
}
#Override
public void mouseReleased(MouseEvent e)
{
isLeftButtonPressed = false;
repaint();
}
//Other MouseListener methods not listed but have to be implemented
}
But it seems as if the left button is never released, even after you actually do so. What could be the problem?

The fundamental in this is incorrect,
These are the mouse events,
MousePressed -> a mouse button is pressed
MouseReleased -> a mouse button is released
MouseClicked -> a mouse button is clicked (pressed and released)
So, when you handle the click event that means mouse is clicked and released.
So i think you have to use mousepressed instead of clicked.
MouseEvent

Method mouseClicked will be called after mouseReleased method so value of isLgetButtonPressed will be true. You have to use MouseEvent.getButton() method to check which mouse button is pressed.

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.

Java applet Displaying Text in window center at Start and following when mouse moves

I am trying to write a program that displays a String on start and then once the mouse moves into the window it follows it around and then stops once mouse exits window. I am able to get the String to follow the mouse but cannot seem to get it to display center at program start and follow mouse. I tried using update but that just drew several String's at once. Any guidance is appreciated.
Here is my code.
import java.awt.*;
import java.applet.*;
import javax.awt.event.*;
public class Follow_Me extends Applet implements MouseListener, MouseMotionListener{
int x;
int y;
String text;
public void init(){
// Add Mouse Listeners
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g){
/* This is where I want to display the String
and then allow it to move wherever the mouse moves
once inside window.
g.drawString("Hello", 230, 150);
but once I set it to the center, my mouseMoved
will not do anything. It will only move with
text if the coordinates are set within method.
*/
g.drawString("Hello", x,y);
}
// Unused mouse listeners
public void mouseReleased (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public void mouseDragged (MouseEvent e){}
public void mousePressed (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseExited (MouseEvent e){}
// Used mouse motion listener
public void mouseMoved (MouseEvent e){
x = e.getX();
y = e.getY();
text = "Hello";
repaint();
}

Adding MouseListeners for JToolBar (events are consumed?)

When adding a MouseListener to a JToolBar,
jToolbar.addMouseListener(new MouseInputAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
log.debug(e.getPoint());
}
});
The event only fires when clicked outside the JToolBar's gripper.
If I override BasicToolBarUI's createDockingListener():
#Override
protected MouseInputListener createDockingListener() {
return new MouseInputAdapter() {
#Override
public void mousePressed(MouseEvent evt) {
log.debug(e.getPoint());
}
}
}
The event will fire when clicked on the gripper.
So my question is, why? Is the MouseEvent consumed in the dockingListener? But I don't see any code that consumes the event.
The MouseEvent is being automatically consumed by the Container at a number of points for a number of different reasons (some relating to how the native peer needs to deal with the event)...
Most notably in the private method Container#processMouseEvent, but it could be consumed before then
This basically means, when you attach a MouseListener to any component, it will consume all mouse events going to any component (or part thereof) that it resides above.
Think of mouse events like rain. When a raindrop hits something, it stops.

MouseListener in Java Swing sometimes not respond

I've implemented right mouse click for open menu listener on my main Jframe, it works fine except one problem. One out of 5 (give or take) clicks it not responding, this can be very annoying for the user. Here is my code:
contentPane = new JPanel();
contentPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3)
{
//Do Stuff
}
}
});
Can you please help me
You won't get clicks from sub-components of contentPane.
I think your problem is that you have added things to your panel. When the user clicks at regions occupied by a sub-component, that sub-component get's the click event.
Quick fix: I would recommend you to add the same mouse listener to all sub-components.
You are not "clicking"
A click is when the mouse is pressed and release really quickly. If you are not careful you might get events for (for instance) "pressed, moved, released" instead of "clicked".
Quick fix: use mouseReleased event instead.
Use this Code instead:
private MouseAdapter listener = new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (downer) {
downer = false;
if (new Rectangle(e.getComponent().getLocationOnScreen(), e.getComponent().getSize())
.contains(e.getLocationOnScreen())) {
downer = false;
// CODE
new Thread(new Runnable(){
public void run(){
//Your Listener code
}
}).start();
/// COde
}
}
}
boolean downer = false;
public void mousePressed(java.awt.event.MouseEvent e) {
downer = true;
}
};
This code only reacts if you press on the component and release on the component AND starts a new Thread for the custom task. This should work allways, because the AWT Thread isnt blocked with long calculations.

How to change JButton background colour while it is pressed?

I am trying to override the default background colour of the JButton while it is pressed; the background colour must stay as long as the button is still pressed.
I tried this code:
button.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent evt) {
button.setBackground(Color.BLUE); // applied after release!!
System.out.println("pressed"); // applied on pressed - OK.
}
});}
mousePressed here doesn't achieve my requirement!!
This line is never invoked: button.setBackground(Color.BLUE);. But this line is invoked: System.out.println("pressed");.
However this line button.setBackground(Color.BLUE); is invoked after releasing the button - Not while pressed!!!
How to achieve my requirement?
Before your mouse-adapter part of code, make a Color object as:
final Color col = button.getBackground();
Then, in your mouse adapter, add this method:
public void mouseReleased(MouseEvent e)
{
button.setBackground(col);
}
This makes your total code to :
final Color col = b.getBackground();
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e)
{
b.setBackground(Color.BLUE);
}
public void mouseReleased(MouseEvent e)
{
b.setBackground(g);
}
});
So, when you press, the color changes to blue, and then when you release the mouse, it changes back to original. This works fine on my computer.

Categories