Question

Java question so right now this code is work perfectly the problem is I also want...

Java question so right now this code is work perfectly the problem is I also want to know if possible to get the X and Y value outside the JFrame?

import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MouseEventDemo extends JFrame implements MouseListener { //It is a class which generate a JFrame and implements MouseListener interface
//These all are text that show x , y coordinates on mouse click event
JLabel lclick;
JLabel lpressed;
JLabel lreleased;   
JLabel lentered;   
JLabel lexited;
public MouseEventDemo()
{
setVisible(true);
setSize(300,300);
lclick=new JLabel("Click At Any Point ");
lpressed=new JLabel("Pressed At Any Point ");
lreleased=new JLabel("Released At Any Point ");
lentered=new JLabel("Entered At Any Point ");
lexited=new JLabel("Exited At Any Point ");
setLayout(new FlowLayout());
//For add on our JFrame
add(lclick);
add(lpressed);
add(lreleased);
add(lentered);
add(lexited);
addMouseListener(this); //It Calls below mouse methods to perform operation on the mouse event
}

@Override
public void mouseClicked(MouseEvent e) {
lclick.setText("Mouse Clicked at ("+e.getX()+","+e.getY()+") ");
}

@Override
public void mousePressed(MouseEvent e) {
lpressed.setText("Mouse Pressed at ("+e.getX()+","+e.getY()+") ");
}

@Override
public void mouseReleased(MouseEvent e) {
lreleased.setText("Mouse Released at ("+e.getX()+","+e.getY()+") ");
}

@Override
public void mouseEntered(MouseEvent e) {
lentered.setText("Mouse Entered at ("+e.getX()+","+e.getY()+") ");
}

@Override
public void mouseExited(MouseEvent e) {
lexited.setText("Mouse Exited at ("+e.getX()+","+e.getY()+") ");
}

//It is a driver program which create a JFrame by calling object of Mouse Event Demo class
public static void main(String[] args) {
new MouseEventDemo();
}
}
/*

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you are talking about detecting clicks outside the window, the short answer is you can’t. You can, however detect the first click outside the window, i.e before the window loses its focus. For that you can add a AWTEventListener with MOUSE_EVENT_MASK or FOCUS_EVENT_MASK. But after a single click, window loses its focus & whenever the window loses it’s focus, no mouse events will be triggered until the focus is regained. If you are talking about just getting x, y coordinates of the window, you can simply use MouseInfo.getPointerInfo().getLocation() to find the current Point where the mouse cursor resides. But this can’t be used to detect the click.

Below is the updated code with the above technique (using AWTEventListener), but you will need to focus the window after every click outside the window. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// MouseEventDemo.java

import java.awt.AWTEvent;

import java.awt.FlowLayout;

import java.awt.MouseInfo;

import java.awt.Point;

import java.awt.Toolkit;

import java.awt.event.AWTEventListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

import javax.swing.JLabel;

public class MouseEventDemo extends JFrame implements MouseListener {

              // It is a class which generate a JFrame and implements MouseListener

              // interface

              // These all are text that show x , y coordinates on mouse click event

              JLabel lclick;

              JLabel lpressed;

              JLabel lreleased;

              JLabel lentered;

              JLabel lexited;

              public MouseEventDemo() {

                           setVisible(true);

                           setSize(300, 300);

                           lclick = new JLabel("Click At Any Point ");

                           lpressed = new JLabel("Pressed At Any Point ");

                           lreleased = new JLabel("Released At Any Point ");

                           lentered = new JLabel("Entered At Any Point ");

                           lexited = new JLabel("Exited At Any Point ");

                           setLayout(new FlowLayout());

                           // For add on our JFrame

                           add(lclick);

                           add(lpressed);

                           add(lreleased);

                           add(lentered);

                           add(lexited);

                           addMouseListener(this); // It Calls below mouse methods to perform

                                                                                                             // operation on the mouse event

                           // the frame will always be on front until the window is closed

                           setAlwaysOnTop(true);

                           // adding AWTEventListener

                            Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

                                         @Override

                                         public void eventDispatched(AWTEvent arg0) {

                                                       // getting current cursor point

                                                       Point p = MouseInfo.getPointerInfo().getLocation();

                                                       // displaying coordinates of clicked point, this will be screen

                                                       // coordinates

                                                       lclick.setText("Mouse Clicked at (" + p.getX() + "," + p.getY()

                                                                                  + ") ");

                                                       // trying to ask for focus

                                                       MouseEventDemo.this.requestFocus();

                                         }

                           }, AWTEvent.FOCUS_EVENT_MASK);

              }

              @Override

              public void mouseClicked(MouseEvent e) {

                           lclick.setText("Mouse Clicked at (" + e.getX() + "," + e.getY() + ") ");

              }

              @Override

              public void mousePressed(MouseEvent e) {

                           lpressed.setText("Mouse Pressed at (" + e.getX() + "," + e.getY()

                                                       + ") ");

              }

              @Override

              public void mouseReleased(MouseEvent e) {

                           lreleased.setText("Mouse Released at (" + e.getX() + "," + e.getY()

                                                       + ") ");

              }

              @Override

              public void mouseEntered(MouseEvent e) {

                           lentered.setText("Mouse Entered at (" + e.getX() + "," + e.getY()

                                                       + ") ");

              }

              @Override

              public void mouseExited(MouseEvent e) {

                           lexited.setText("Mouse Exited at (" + e.getX() + "," + e.getY() + ") ");

              }

              // It is a driver program which create a JFrame by calling object of Mouse

              // Event Demo class

              public static void main(String[] args) {

                           new MouseEventDemo();

              }

}

//OUTPUT

Add a comment
Know the answer?
Add Answer to:
Java question so right now this code is work perfectly the problem is I also want...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show...

    In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...

  • Java II. 20. What is the default layout manager of a JPanel object? 21. Say you...

    Java II. 20. What is the default layout manager of a JPanel object? 21. Say you want to display some buttons in a table-like structure. What would be the best layout manager for that? 22. The Color and the Font classes are in what package? 23. What is the keyword used to inherit an interface into a class? 24. What is the keyword used to inherit a class into another class? 25. What kind of class is the code in...

  • Modify the code to turn the text area background to the color YELLOW if you click...

    Modify the code to turn the text area background to the color YELLOW if you click an "x" (lower or uppercase)? package com.java24hours; import javax.swing.*; import java.awt.event.*; import java.awt.*; public class KeyViewer extends JFrame implements KeyListener { JTextField keyText = new JTextField(80); JLabel keyLabel = new JLabel("Press any key in the text field."); public KeyViewer() { super("KeyViewer"); set LookAndFeel(); setSize(350, 100); setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ; keyText.addKeyListener(this); BorderLayout bord = new BorderLayout(); set Layout (bord); add (keyLabel, BorderLayout. NORTH); add (keyText, BorderLayout....

  • "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import...

    "Polygon Drawer Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked." import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.*; public class PolygonDrawer extends Applet implements MouseListener{ //Declares variables    private int[] X, Y;    private int ptCT;    private final static Color polygonColor = Color.BLUE; //Color stuff    public void init() {        setBackground(Color.BLACK);        addMouseListener(this);        X = new int [450];        Y =...

  • 1) Consider the following Java program: 1 public class HelloWorld { 2     // My first program!...

    1) Consider the following Java program: 1 public class HelloWorld { 2     // My first program! 3     public static void main(String[] args) { 4         System.out.println("Hello, World!"); 5     } 6 } What is on line 1? a. a variable declaration b. a statement c. a method (subroutine) definition d. a comment e. a class definition 2) Which one of the following does NOT describe an array? a. It can be used in a for-each loop. b. It has a numbered sequence...

  • JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...

    JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to maintain a list of shapes drawn as follows: Replace and upgrade all the AWT components used in the programs to the corresponding Swing components, including Frame, Button, Label, Choice, and Panel. Add a JList to the left of the canvas to record and display the list of shapes that have been drawn on the canvas. Each entry in the list should contain the name...

  • Can you please help me to run this Java program? I have no idea why it...

    Can you please help me to run this Java program? I have no idea why it is not running. import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @SuppressWarnings({"unchecked", "rawtypes"}) public class SmartPhonePackages extends JFrame { private static final long serialVersionID= 6548829860028144965L; private static final int windowWidth = 400; private static final int windowHeight = 200; private static final double SalesTax = 1.06; private static JPanel panel;...

  • Please I need your help I have the code below but I need to add one...

    Please I need your help I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation. import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; import java.util.Random; public class TicTacToe extends JFrame implements ChangeListener, ActionListener { private JSlider slider; private JButton oButton, xButton; private Board...

  • Can you fix my error? I created a program that changes labels every second in Java....

    Can you fix my error? I created a program that changes labels every second in Java. But, it does not change. And, it will starts with second label. This is also an error. import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class Map2 extends JFrame{ JPanel panel; JLabel pic; Timer tm; int x = 0; String ly = "<html> " + "<br> <font size='10' color='red'> <b> 111111111 <b/> </font>...

  • Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button...

    Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button just hit enter on keyboard to try number -Remove Button Quit import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; // Main Class public class GuessGame extends JFrame { // Declare class variables private static final long serialVersionUID = 1L; public static Object prompt1; private JTextField userInput; private JLabel comment = new JLabel(" "); private JLabel comment2 = new JLabel(" "); private int...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT