How do you construct a MouseEvent? - java

I know this question is very simple, but I cannot figure out how to construct it. It seems to have a lot of parameters, and I not only don't know what to put in them, but I also don't even know what a component is. It would be great if someone could explain using basic concepts. Thanks

There are 3 steps you need:
1. You have to implement the Mouselistener interface in your GUI class
2. Add the listener to a GUI element which it should listen to
3. Implement the event listener for your specific mouse event (will also be required by the compiler after you add the interface to your class)
For help: tutorial from Oracle https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

MouseEvent can not be effectively used without MouseListener.
To use MouseListener, you have to either use:
public class StackTest implements MouseListener{
public static void main(String[] args){
}
public void mouseClicked(MouseEvent arg0){
}
public void mouseEntered(MouseEvent arg0){
}
public void mouseExited(MouseEvent arg0){
}
public void mousePressed(MouseEvent arg0){
}
public void mouseReleased(MouseEvent arg0){
}
Or, you would use
component.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0){
}
public void mouseEntered(MouseEvent arg0){
}
public void mouseExited(MouseEvent arg0){
}
public void mousePressed(MouseEvent arg0){
}
public void mouseReleased(MouseEvent arg0){
}
});
Either works, just as long as the component is able to have a MouseListener implemented into it. Those five methods are required too, and they all have their own invokes.
mouseClicked
This is invoked when the user presses any button on the mouse within the component.
mouseEntered
This is invoked when a user's mouse enters the component's region.
mouseExited
This is invoked when a user's mouse leaves the component's region.
mousePressed
This is invoked when a user presses their Left Mouse Button on the component.
mouseReleased
This is invoked when a user releases any of the buttons on the mouse after it has been pressed over the component
NOTE: mouseClicked will ALWAYS be invoked before mouseReleased, and the same goes with mouseEntered and mouseExited, respectively.
These methods will also be invoked regardless of whether or not there is any code in them.
Now, a component is an object that descends from the Component class. Components are things such a JButtons, JPanels, JFrames, etc. and all the modern components you see are from from the javax.swing package. For example, you may have seen the JOptionPane.
The JOptionPane is just a JFrame, a JLabel, and a JButton.
All of those are components that can have an Event Listener. An event listener does exactly what it says. It listens for specific events. MouseListener for example, listens for events involving the user's Mouse.
You can learn more about components here

Related

Mouse listener throws no errors but doesn't fire (java)

I am following code I found on geeksforgeeks but the mouse listener isn't firing. I suspect that somehow the implementation of runnable is locking access to my board object, but I'm not sure. I'm in a similar boat to the OP of this post.
public class Game extends Canvas implements MouseListener {
JFrame jf = new JFrame();
Game() {
jf.getContentPane().add(this, BorderLayout.CENTER);
jf.setSize(new Dimension(500,500+30));
jf.setVisible(true);
jf.addMouseListener(this);
}
public void mouseClicked(MouseEvent e){
System.out.println("Hello World!");
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public static void main(String[] args){
Game game = new Game();
}
}
I suspect but doubt that the mouse listener may not be functioning properly due to it being created in a non-static method, but I doubt that that is the problem. I've tried moving the declaration to the beginning of the constructor, but that didn't help.
The events will only register on the component which has focus. Which, in your program is your main panel, the Game class. So a quick fix would be just to change:
jf.addMouseListener(this);
to
addMouseListener(this);
But you should add the listener to any component you might want to get the events on, i.e. your main panel, the content pane, and jframe too.
The problem was with using Canvas instead of JPanel as the superclass. When I switched, the mouse listener started firing.

Why Listeners are interdependent on one another in Java?

I have written MineSweeper game. In that I have two Listeners for a button as,
class SampleClass extends MouseAdapter implements ActionListener {
//Some code here
public void actionPerformed(ActionEvent event){ // Buttons listener..
System.out.println("I came here to actionPerformed.");
//Some Code
}
public void mouseClicked(MouseEvent event) { //Mouse listener..
System.out.println("I came here to MouseClicked.");
//Some Code
if(event.getButton() == MouseEvent.BUTTON3){..}//If Right Mouse Button Is Clicked!!
else if(event.getButton() == MouseEvent.BUTTON1){..}//If Left Mouse Button Is Clicked!!
}
}
What I observed is , whenever left button of mouse is clicked, the only actionPerformed is called and not mouseClicked. But on the click of the right button of mouse, mouseClicked is called ( and as in normal case , actionPerformed is not called).
But, When I remove the ActionListener, then on both clicks of left and right mouse buttons mouseClicked is called and works perfectly fine.
I thought, the two listeners to be two different independent threads, listening for the events, But why one depends on other?
No two listeners are not dependent on each other. It is the property of JButton to fire an Action if it is pressed, either by space bar , or calling doClick or by left click of mouse. That's why actionperformed is called by default(given that the ActionListener is registered with it) when you press the JButton by left click of mouse but before actionPerformed is called , mousePressed event is called. And in case the ActionListener is not registered with the JButton , MouseEvent comes into play and the required action is performed. Two Listeners work independently of each other. In fact actions are fired in a proper sequence.. for Example for JButton if ActionListener and MouseListener both are registered .. Then the sequence of actions fired is as follows:
mousePressed()
actionPerformed()
mouseReleased()
mouseClicked()
This code would make you clear about these points.:
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
class Listeners extends JFrame
{
public void prepareAndShowGUI()
{
setTitle("Listeners dependency");
JButton button = new JButton("Click");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent evt)
{
System.out.println("Action Listener has listened.");
}
});
button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
System.out.println("Mouse Clicked.");
}
public void mousePressed(MouseEvent evt)
{
System.out.println("Mouse pressed.");
}
public void mouseReleased(MouseEvent evt)
{
System.out.println("Mouse Released.");
}
});
getContentPane().add(button);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String stp[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Listeners listen = new Listeners();
listen.prepareAndShowGUI();
}
});
}
}
on Clicking the JButton following output is obtained:
Mouse pressed.
Action Listener has listened.
Mouse Released.
Mouse Clicked.
AWT's MouseListener and MouseMotionListener handling acts very strange sometime.
But as what I think events should not interfere with each other.
If a component has no mouse listener
then mouse events are raised up to the parent container. This means you
can get away with listening to a parent component, and still receive
events for all of its children.In the above usecase which if some other code adds a mouse listener to a child component than mouse events will not bubble up to parent container.
This is really a bad design.
I prefer to use mouse listener if and only if I am writing a subclass of a JComponent or a PL&F because they can get overidden by other events listeners.So i guess this is what happened in your case.And one suggestion is to use EventQueue that should serve your purpose.

How to stop JButton being enabled when mouse hovers over it?

I created a frame using NetBeans. The frame has two buttons A and B. Button A is initially disabled. It is to be enabled only when button B is clicked.
public newFrame() { //newFrame is the name of the frame that has buttons A&B
initComponents();
btn_A.disable();
}
private void btn_BActionPerformed(java.awt.event.ActionEvent evt)
{
btn_A.enable();
}
The problem is that button A becomes active/enabled when the mouse is moved over it ie inspite of whether button B is clicked or not. How can i fix this?
I want button A to be enabled only after button B is clicked and not as a result of any other event.
Use btn_A.setEnabled(false) instead of btn_A.disable()
btn_A.enable() is a deprecated method.
To do this task, you could replace it by btn_A.setEnabled(false); to disable the button and btn_A.setEnabled(true); to enable the button.
Also, one more suggestion is, add statements like the following in your method if you feel something wrong happening:
System.out.println("Some statement relevant to the method");
The main aim of those extra statements being you know when the method was actually executed.
Try the following code:
button. addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
button.setEnable(true);
}
public void mouseExited(MouseEvent me) {
button.setEnable(false);
}
});

Drawing border around JLabel when selected, like the Buttons

I was trying to paint border around JLabel when it is clicked. Just like JButtons are painted.
I thought it would be easy but I failed to do the job.
I tried to figure out what happens to JButtons when clicked by putting breakpoints in source codes. But I got lost, however, I have a feeling that javax.swing.plaf and its subpackages are what I need.
Am I right? Is there a simpler way to do the job.
Here is an example:
You could add MouseListener to your label and setup a border in mousePressed/mouseReleased methods. Here is a simplified example:
label.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent arg0) {
label.setBorder(BorderFactory.createLineBorder(Color.black));
}
#Override
public void mouseReleased(MouseEvent arg0) {
label.setBorder(null);
}
});
Also, as an alternative you can make a button with a flat style that will look like a label. This answer can be useful.

Hover over multiple buttons in Java?

Is it possible, in Java, when you hover over a single button, to make the program think you are hovering over multiple buttons?
I'm using a multi-dimensional array with buttons and want to be able to have 5 buttons be hovered over at a time. (All the buttons near the actual hover).
Any ideas on how to do this?
Note: I'm not using JButtons, just regular buttons. (awt.Button)
EDIT
I obviously wasn't clear enough, and I apologize for that.
Here is a screenshot of what I'm looking for:
So, the cursor is hovering over the first gray space, and all of the space next to it have a different background, however, they are not considered as being hovered over, which if what I need.
Assuming you are using a MouseListener, when the mouseEntered(MouseEvent e) method is called on the master button, explicitly call the same method on all of the listeners of all of the other buttons, passing the event you have been given. Ditto for the mouseExited(MouseEvent e) method.
It's up to you to maintain a reference from the master button to the subordinate buttons.
The subordinate buttons' listeners will receive an event that refers to the master button. If necessary, create your listeners with a reference to the button that they are attached to, so that you can operate on that button when receiving an event.
EDIT:
This is the kind of thing I'm talking about. Does it help?
final List<Button> subordinateButtons = Arrays.asList(new Button(), new Button(), new Button());
Button myButton = new Button();
myButton.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
for (Button subordinateButton : subordinateButtons) {
subordinateButton.setBackground(Color.GRAY);
}
}
public void mouseExited(MouseEvent e) {
for (Button subordinateButton : subordinateButtons) {
subordinateButton.setBackground(Color.LIGHT_GRAY);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
});
There's no reason why you can't keep a reference from a MouseListener to a List<Button>. If it's the business of the listener to work on those buttons then design your classes so that it happens.

Categories