How to check if mouse is pressed on JComponent - java

I have a JComponent, and I want it do preform a piece of code when the component is pressed. Can someone help me?

JComponent comp = new JPanel();
comp.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// Place your code here
}
});

Assuming you have a Class that extends JComponent
import java.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyClass extends JComponent{
public MyClass(){
//Other code
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// Place your code here
}
});
//Other code
}
}

Related

Why am i getting this error from getSource method in MouseAdapter?

I was trying to change the text "Java" to "Love Java" by using MouseAdapter. The text "Java" comes out when mouseEntered and "Love Java" comes out when mouseExited. So I created class MyMouse extends MouseAdapter and trying to use the methods.
But there is the error message "The method getSource() is undefined for the type MouseEvent". When I searched it, this code is nothing wrong with it but I don't know why I'm getting this error message, and also of course the result is not working.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEvent extends JFrame{
MouseEvent(){
setTitle("Practicing mouse event");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lb = new JLabel("Java");
MyMouse mym = new MyMouse();
lb.addMouseListener(mym);
lb.setSize(300,100);
add(lb);
setSize(400,200);
setVisible(true);
}
public static void main(String[] args) {
new MouseEvent();
}
}
class MyMouse extends MouseAdapter{
public void mouseEntered(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Love Java");
}
public void mouseExited(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Java");
}
}
The MouseEvent object e you are using inside public void mouseEntered(MouseEvent e) or public void mouseExited(MouseEvent e) should be from java.awt.event.MouseEvent.
But, as you have named your main class also as MouseEvent, in that case the MouseEvent object e inside mouseEntered() and mouseExited() methods are actually the object of your main class. That's why it was searching for getSource() method in your main class and failed.
Please change your main class name to something other than MouseEvent. For example:
public class MyMouseEvent extends JFrame {
MyMouseEvent() {
...
...
public static void main(String[] args) {
new MyMouseEvent();
...
The problem can be solved through these changes to the code:
Rename the main class of the program so that its name does not conflict with that of the class (java.awt.event.MouseEvent) imported from Java library.
Add #Override annotations to mouseEntered and mouseExited methods to avoid compiler warnings
Call setVisible(true) on the frame to display after instantiation
Here is the working example with the above mentioned changes:
// File name: Demo.java
// This name was chosen to avoid conflict with java.awt.event.MouseEvent
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyMouse extends MouseAdapter{
// Add #Override annotation to overridden methods
#Override
public void mouseEntered(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Love Java");
}
// Add #Override annotation to overridden methods
#Override
public void mouseExited(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Java");
}
}
public class Demo extends JFrame{
Demo() {
setTitle("Practicing mouse event");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lb = new JLabel("Java");
MyMouse mym = new MyMouse();
lb.addMouseListener(mym);
lb.setSize(300,100);
add(lb);
setSize(400,200);
}
public static void main(String[] args) {
Demo demo = new Demo();
// Display the frame
demo.setVisible(true);
}
}
Output:
> javac Demo.java
> java Demo

AWT Frame does not handle events

The frame opens and close normally but mouse click doesn't work.
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Create a frame window that responds to mouse click
public class AWT3 extends Frame {
String Mmsg="";
int mouseX=0, mouseY=0;
public AWT3() {
addWindowListener(new MyWindowwAdapter(this));
addMouseListener(new MyMouseeAdapter(this));
}
public void paint(Graphics g){
g.drawString(Mmsg, mouseX, mouseY);
}
public static void main(String args[]){
AWT3 awt3 = new AWT3();
awt3.setSize(new dimension(500, 500));
awt3.setTitle("Window framee");
awt3.setVisible(true);
}
}
class MyWindowwAdapter extends WindowAdapter{
AWT3 awt3;
public MyWindowwAdapter(AWT3 awt3) {
this.awt3=awt3;
}
public void windowClosing(WindowEvent we){
awt3.setVisible(false);
}
}
class MyMouseeAdapter extends MouseAdapter{
AWT3 awt3;
public MyMouseeAdapter(AWT3 awt3) {
this.awt3=awt3;
}
public void MouseClicked(MouseEvent me){
awt3.Mmsg="the mouse is clicked";
awt3.mouseX= me.getX();
awt3.mouseY=me.getY();``
awt3.repaint();
}
}
From what it looks like, this code won't compile. You have an error that you need to fix:
awt3.setSize(new dimension(500, 500));
to
awt3.setSize(new Dimension(500, 500));
and add the proper import java.awt.Dimension as pointed out by others.
Another mistake is that MouseClicked(MouseEvent me) is not overriding the super class method from MouseAdapter as its syntactically wrong (super class method starts with small case). Change it to mouseClicked(MouseEvent me) (add the optional #Override annotation if you wish).
The method name should be public void mouseClicked(MouseEvent me)
instead of public void MouseClicked(MouseEvent me).
mouseClicked() is when the mouse button has been pressed and released.
mousePressed() is when the mouse button has been pressed.
Your code is working. tested on java 1.7. only the problem I saw, was with out importing the java.awt.Dimension class you are trying to create a new dimension(500, 500); although the class name is in simple form you can fix this error and try the code.

Mac: Full Screen JFrame losing keybindings from mouseadapter

On my Mac, fullscreen JFrames initially have key bindings that do not work, and the computer outputs alert beeps each time I try to type. There is a workaround, though, after fully initializing my JFrame, I added these lines of code and all the errors stopped:
setVisible(false);
setVisible(true);
Here's the source of this workaround: http://mail.openjdk.java.net/pipermail/macosx-port-dev/2012-November/005109.html
Another problem which is yet to be solved is adding a mouse adapter to my full screen JFrame application. Whenever I clicked, the focus changed--to where, I couldn't quite tell, but setting the inputmap of my keybindings to each one of the three options didn't help.
I even tried redoing the workaround when the mouse was clicked by adding this:
event.getComponent().setVisible(false);
event.getComponent().setVisible(true);
but to no avail.
Here is an SSCCE of the problem (it will only show up on a mac):
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class FocusTest extends JFrame{
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public FocusTest() {
MyPanelDescendent myPanelDescendent = new MyPanelDescendent();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(myPanelDescendent);
pack();
setLocationByPlatform(true);
setVisible(true);
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
dispose();
System.exit(0);
}
};
getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(escapeKeyStroke, "ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escapeAction);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
gs.setFullScreenWindow(this);
setVisible(false);
setVisible(true);
}
private class MyPanelAscendent extends JPanel{
public MyPanelAscendent() {
setFocusable(true);
requestFocusInWindow();
getInputMap(0).put(KeyStroke.getKeyStroke("pressed A"), "pressed");
getActionMap().put("pressed", new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("a")) {
System.out.println("a was pressed");
}
}
});
addMouseListener(new MyAdapter());
}
}
private class MyPanelDescendent extends MyPanelAscendent {
public MyPanelDescendent() {
super();
}
}
private class MyAdapter extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent event) {
event.getComponent().setVisible(false);
event.getComponent().setVisible(true);
System.out.println("clicked");
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FocusTest();
}
});
}
}
If you press the a key, then click, then do it again, it will not work. The same goes for the escape key: if you click then try to use it, it won't work.
here is an example for fullscreen posted by trashgod which I've also found impossible to make work with both keybindings, fullscreen, and a mouse adapter at the same time.

Can't get MouseListener to work

Ok, I am trying to use MouseListener for the first time, but I'm not having much luck. My program compiles fine but the MouseListener Events don't seem to do anything. Here is my code:
import java.awt.color.*;
import java.awt.font.*;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class yo implements MouseListener {
Image image;
JFrame frame = new JFrame();
JLabel heloo = new JLabel("yo");
JPanel panel = new JPanel()
{
#Override
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
//ImageIcon i = new ImageIcon("hi.jpg");
//image = i.getImage();
//g.drawImage(image,150,150,null);
//g.drawString("Hello",100,100);
//g.drawString("Hi",50,50);
}
};
public yo()
{
frame.add(panel);
frame.setTitle("Hello");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
panel.add(heloo);
}
public void mouseClicked (MouseEvent Event)
{
heloo.setText("Hi");
System.out.println("Hi");
}
public void mouseEntered (MouseEvent Event)
{System.out.println("Hi");}
public void mouseExited (MouseEvent Event)
{}
public void mousePressed (MouseEvent Event)
{}
public void mouseReleased (MouseEvent Event)
{}
public static void main(String[] args)
{
new yo();
}
}
By not doing anything I mean that the system doesn't output text to command line or change the JLabel.
Any help on how to get it to work would be great, thanks.
p.s. I'm a noob so, be nice.
Read the Swing tutorial on How to Write a MouseListener.
You didn't add the listener to any component.
put
frame.addMouseListener(this);
in the constructor
You made a yo a MouseListener, but you didn't add it to anything.
You need to use .addMouseListener(this); on each component you want to listen to.
e.g.
frame.addMouseListener(this), or if in a static method frame.addMouseListener(myInstanceOfYo);
try
public yo()
{
frame.add(panel);
frame.setTitle("Hello");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
panel.add(heloo);
frame.addMouseListener(this);
}
Edit:
I would also suggest you change your test text in each MouseListener method to be unique, so it's easier to see which was called, and when. Also, make the parameter name start with a lower case letter (Event becomes event), it's just good practice.
i.e.
public void mouseClicked (MouseEvent event)
{
heloo.setText("Hi");
System.out.println("Clicked.");
}
public void mouseEntered (MouseEvent event)
{
System.out.println("Entered.");
}
public void mouseExited (MouseEvent event)
{
System.out.println("Exited.");
}
public void mousePressed (MouseEvent event)
{
System.out.println("Pressed.");
}
public void mouseReleased (MouseEvent event)
{
System.out.println("Released.");
}

Problems With MouseListener

I'm writing a game in java. The problem here is I wrote my game to run in a JFrame, not thinking that i would want to add menus and a results screen and all that good stuff. The game itself runs great in the JFrame. What i decided to do, though, was turn my JFrame into a JPanel, create a separate class for my JFrame and then just add my JPanel to the frame. Everything works just peachy except my MouseListener no longer does a darn thing. Can someone tell me how to make this work or a different idea of how this can be done?
/////UPDATE
So apparently i found an answer while recreating the problem.... I just need the figure out the difference between my game code and the test code.
Here is the example i wrote up to try and reproduce the problem.. Oddly enough this works. Now I'm even more confused. So apparently this is ok:
//Class for the JFrame
package mousetest;
import java.awt.Color;
import javax.swing.JFrame;
public class MouseTest extends JFrame{
public static void main(String[] args) {
MouseTest test = new MouseTest();
}
public MouseTest(){
//create teh board
Board game = new Board();
//framestuff
setSize(406, 630);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
setBackground(Color.black);
add(game); // add it
}
}
========================================================================
//Class for the JPanel that my game is in
package mousetest;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Board extends JPanel{
JLabel testlabel = new JLabel("testtext");
//CONSTRUCTOR
public Board(){
setBackground(Color.WHITE);
testlabel.addMouseListener(new Mousehandle());
setVisible(true);
add(testlabel);
}
// control ALLTHECLICKS!!!!!
class Mousehandle implements MouseListener{
public Mousehandle(){
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("mouse down");
}
}
public void mouseReleased(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("mouse up");
}
}
public void mouseEntered(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("rollover");
}
}
public void mouseExited(MouseEvent e) {
if(e.getSource() == testlabel){
System.out.println("roll off");
}
}
public void mouseDragged(MouseEvent e){
}
}
}

Categories