Open JFrame on same screen(monitor) as JavaFX' 8 dialog - java

I am working on application that has a usual login window (JavaFX' 8 dialog), and then on accept it opens new window (JFrame). If it runs in multi-monitor environment, it should work the way, that JFrame would be opened on the same monitor where JavaFX' 8 dialog was closed.
Right now I could open JFrame on monitor that I can choose manually using
GraphicsEnvironment, but at this point I can't figure out on which monitor JavaFX' 8 dialog was closed. Any ideas? Thank you.

Maybe you could save your Position when you close your JavaFX dialog:
private void saveWindowPosition() {
Preferences userPrefs = Preferences.userNodeForPackage(getClass());
userPrefs.putDouble("stage.x", primaryStage.getX());
userPrefs.putDouble("stage.y", primaryStage.getY());
}
and read it out like this:
private void restoreWindowPosition() {
Preferences userPrefs = Preferences.userNodeForPackage(getClass());
// get window location from user preferences: use x=100, y=100 as
// default
double x = userPrefs.getDouble("stage.x", 100);
double y = userPrefs.getDouble("stage.y", 100);
primaryStage.setX(x);
primaryStage.setY(y);
}

Well, here is what worked for me:
/**
* As an argument you pass a Scene(of Java FX 8 Dialog in my example),
* by closing it you want JFrame to open on same monitor.
**/
public static int getActiveStageLocation(Scene scene){
List interScreens = Screen.getScreensForRectangle(scene.getWindow().getX(),
scene.getWindow().getY(),
scene.getWindow().getWidth(),
scene.getWindow().getHeight());
Screen activeScreen = (Screen) interScreens.get(0);
Rectangle2D r = activeScreen.getBounds();
double position = r.getMinX();
return (int) position;
}
Then you simple set location of your JFrame:
/**
* Some code for instantiating frame and so on....
* Parameter scene you could get for example from your FXML
**/
myFrame.setLocation(getActiveStageLocation(scene), myFrame.getY());
myFrame.setVisible(true);

Related

Custom splash screen using JWindow/JPanel doesn't load image correctly when attempting to display it a second time

Thank you in advance for any attempts at trying to help me figure this one out. I've searched all over stack and google and haven't been able to find anything similar to the problem I am having.
I am designing a small program using NetBeans that switches between multiple frames
login screen > settings screen > main screen
My program can take a while in-between frames to load the next one due to a large amount of frame initialization code. To prevent it from looking like the program is unresponsive. I wrote code which displays an intermediary splash screen JWindow which performs all the initialization for the next frame. I realize that there is a splash screen class, but I could not get it to work as desired, this custom implementation of mine does almost everything I need except when I attempt to display the splash screen a second time, during a single program run, the image does not show up on the JWindow.
So run program > splash screen (works) > login > splash screen (image does not load) > settings.
Here is a sample clip of code which displays the splash screen JWindow:
public class Splash extends JPanel {
private static Calendar date;
private static long startTime;
private static final long MAX_TIME = 3000l;
public static final int LOAD_LOGIN = 0;
public static final int LOAD_SETTINGS = 1;
public static JWindow win;
private final ImageIcon img;
public Splash() {
date = Calendar.getInstance(TimeZone.getTimeZone("EST"), Locale.ENGLISH);
img = new ImageIcon("loader.gif");
startTime = date.getTimeInMillis();
this.setSize(300, 300);
win = new JWindow();
win.setSize(300, 300);
win.getContentPane().add(this);
Login.centerWindow(win); // method from login class that centers window
win.setVisible(true);
}
public void runSplash(int flag) {
if (flag == LOAD_LOGIN)
firstRunCheck();
else {
initSettings();
}
long currTime = date.getTimeInMillis();
// holds splash display for at least 3 secs
while ((currTime - startTime) < MAX_TIME) {
currTime = System.currentTimeMillis();
}
win.dispose(); // has been replaced with win.setVisible(false) before,
// same problem
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
//I have read several other questions and sample codes on stack and google
but using this method is the only way for me to get the animated gif image to
load correctly
g2.drawImage(img.getImage(), null, this);
}
}
In order to display this splash screen I instantiate it using new Splash().runSplash(value); where value runs the method that loads the following frames required values.
When I first begin run the program everything works perfectly. When I attempt to move from the login screen to the settings screen the JWindow loads but it just displays as a blank frame.
The program works fine still, the settings frame eventually loads, but the image never shows up and the window just closes. I am unsure as to what the problem is the class is instantiated the exact same way as the first time.
I suspect perhaps I may be incorrectly disposing of resources, but win.dispose() appears to be the correct method according to some of the other problems I have read.
Any help is appreciated thank you.
UPDATE: I am still attempting to resolve this problem. I have used a variety of different implementations to display the splash screen. I have used implementations which use a JLabel instead of JPanel, and use setIcon instead of overriding paintComponent. But the same result is observed whenever the implemented splash screen class is called a second time the image does not appear. Since different implementations are also not working I can only assume that that perhaps I have too many events in the event queue or something. To clarify.
My main method is in the Splash class detailed above. I call the class in the main method using new Splash.runSplash(value). This call works perfectly. I then call the login JFrame using:
if (value == LOAD_LOGIN) //RUN_LOGIN is a final variable int
{
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
/* I have also tried this without the invokeLater
command and simply using new Login().setVisible(true).
The program still runs fine, but the image still
does not display */
new Login().setVisible(true);
}
});
}
This call is made at the end of the runSplash(value) method. After the user inputs the correct login information they are taken to the splash screen again using new Splash().runSplash(value) on this call however I cannot get the image to show up on the JWindow.
dispose() method releases the resource. to be able to use it again you have to use setVisible(false) and when you be sure that your code will not use this window again then only use dispose().In your case after first splash just use setVisible(False) and dispose after the second time when setting frame loads if you really want it so.

Minimize/maximize parent JFrame

Im making a quiz application. And when a team pushed their button, they aren't allowed to still see the question or see the video/audio piece. This kind of information is displayed in the quizview ( this is a jpanel ) added to a parent JFrame. What i'm trying to do is minimize the JFrame when a button is pushed from the teams. This works perfectly. If a button is pushed the administator get a pop up in his view. If the answer is incorrect the JFrame should be maximized again. So when he pushes a button if the answer is incorrect, a boolean will be set on true in the quiz model ( $maximize ). We update the views then. In the update of the view im checking if the boolean is set on true. If it is true, i call the maximize method. And maximize it again when the answer is wrong. Minimizing works perfectly, but maximizing not.
Anyone knows what's wrong?
This is my code in the view, this view is a JPanel in the bigger JFrame, where the maximizing happens :
public void update(Observable arg0, Object arg1) {
$question = (Question) arg1;
if(((QuizModel) getModel()).getMaximize()) /* Only maximize the JFrame when needed */
maximizeFrame(); /* Maximize the frame first */
repaint();
}
/**
* Maximize the parent JFrame so the teams can see the question
*/
protected void maximizeFrame() {
System.out.println("MAXIMIZE");
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setState(JFrame.MAXIMIZED_BOTH);
}
The minimizing occurs when a team pushed their button, here is the code :
/**
* If a button gets pressed we call this function
* #param team the team that pressed their button
*/
protected void buttonPressed(int team) {
/* Check if a button is pressed */
if(((QuizModel) getModel()).getTeamPressed() > 0)
$isPressed = true;
else
$isPressed = false;
/* If there hasn't been pressed yet and the question is not null */
if(!$isPressed && $question != null){
minimizeFrame(); /* Minimize the frame */
/* If this question has a media path we need to pause the audio/video, we also check if the user has installed vlcplayer and selected the right path */
if($question.getMediaPath() != null && QuizSoftwareModel.$vlcPath != null)
((QuizController)getController()).pause(); /* Pause the video */
/* Give a pop up message to the admin that a team has pushed their button */
((QuizController)getController()).showScoreView(team);
}
}
/**
* Minimize the parent JFrame so the teams can't see the question anymore
*/
protected void minimizeFrame() {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setState(JFrame.ICONIFIED);
}
[EDIT] Reduced the code.
Thanks!
The solution is using topFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); instead of setState.
Setstate only sets the state of the current frame, because i needed the parent frame i needed to use setExtendedState.
Also missed some booleans to maximize/minimize when needed.

How to write a splash screen?

I'm making a game using Java.
At the moment, I have several classes. The important ones are:
the LevelBuilder class which, upon it's default constructor being called will create a jframe with the required components and then run a gameloop thread which will update even 1/20th of a second using a backbuffer.
The other class is the MainMenu class which i want to have the main method in and to display my logo in a JFrame.
In the end I want to have the MainMenu draw a splash screen to the JFrame, and then after 5 seconds the LevelBuilder to draw inside the original JFrame, without creating a new one.
Sorry if it's a basic question, I just started learning Java.
Well a splash-screen can simply be added to your jar via the manifest.
The problem is by default it will only show for as long as it takes Swing app to load. Thus the 2nd (3rd 4th etc) execution(s) shows the splash-screen fast as JVM and classes etc used by GUI have already been loaded.
In my game to create a splash that stays for longer I had these 2 methods:
/**
* This will render the splash for longer than just loading components
*
* #return true if there is a splash screen file supplied (set via java or
* manifest) or false if not
* #throws IllegalStateException
*/
private boolean showSplash() throws IllegalStateException {
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
return false;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
return false;
}
for (int i = 0; i < 100; i++) {//loop 100 times and sleep 50 thus 100x50=5000milis=5seconds
renderSplashFrame(g);
splash.update();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
splash.close();
return true;
}
private void renderSplashFrame(Graphics2D g2d) {
//draw anyhting else here
}
which will be called something like:
JFrame frame=...;
...
//show splash
if (!showSplash()) {
JOptionPane.showMessageDialog(null, "SplashScreen could not be shown!", "Splash Error: 0x003", JOptionPane.ERROR_MESSAGE);
}
// set JFrame visible
frame.setVisible(true);
frame.toFront();
Please note as showSplash() says it will return false if there is no splash-screen supplied i.e you have not added one to the manifest.
I also would recommend a read on How to Create a Splash Screen if you already haven't.
Also see this other similar answer/question: Make splash screen with progress bar like Eclipse

JColorChooser: Save/restore recent colors in Swatches panel

I am using a JColorchooser at various places in an application. There can be multiple instances of the panel that can invoke a JColorChooser.
The "Swatches" panel in the chooser has an area of "recent" colors, which only persists within each instance of JColorChooser. I would like to (a) have the same "recent" colors in all my choosers in my application, and (b) to save the colors to disk so that these colors survive close and restart of the application.
(At least (a) could be solved by using the same single chooser instance all over the whole app, but that apears cumbersome because I would need to be very careful with attached changelisteners, and adding/removing the chooser panel to/from various dialogs.)
I did not find any method that lets me set (restore) these "recent" colors in the chooser panel. So to me, it appears that the only ways of achieving this would be:
serialize and save / restore the whole chooser (chooser panel?)
or
create my own chooser panel from scratch
Is this correct, or am I missing something?
BTW: I would also like to detect a double click in the chooser, but it seems hard to find the right place to attach my mouse listener to. Do I really need to dig into the internal structure of the chooser panel to do this? (No, it does not work to detect a second click on the same color, because the change listener only fires if a different color is clicked.)
As you noticed, there is no public api to access the recent colors in the DefaultSwatchChooserPanel, even the panel itself isn't accessible.
As you'll need some logic/bean which holds and resets the recent colors anyway (plus the extended mouse interaction), rolling your own is the way to go. For some guidance, have a look at the implementation of the swatch panel (cough ... c&p what you need and modify what you don't). Basically, something like
// a bean that keeps track of the colors
public static class ColorTracker extends AbstractBean {
private List<Color> colors = new ArrayList<>();
public void addColor(Color color) {
List<Color> old = getColors();
colors.add(0, color);
firePropertyChange("colors", old, getColors());
}
public void setColors(List<Color> colors) {
List<Color> old = getColors();
this.colors = new ArrayList<>(colors);
firePropertyChange("colors", old, getColors());
}
public List<Color> getColors() {
return new ArrayList<>(colors);
}
}
// a custom SwatchChooserPanel which takes and listens to the tracker changes
public class MySwatchChooserPanel ... {
ColorTracker tracker;
public void setColorTracker(....) {
// uninstall old tracker
....
// install new tracker
this.tracker = tracker;
if (tracker != null)
tracker.addPropertyChangeListener(.... );
updateRecentSwatchPanel()
}
/**
* A method updating the recent colors in the swatchPanel
* This is called whenever necessary, specifically after building the panel,
* on changes of the tracker, from the mouseListener
*/
protected void updateRecentSwatchPanel() {
if (recentSwatchPanel == null) return;
recentSwatchPanel.setMostRecentColors(tracker != null ? tracker.getColors() : null);
}
// the mouseListener which updates the tracker and triggers the doubleClickAction
// if available
class MainSwatchListener extends MouseAdapter implements Serializable {
#Override
public void mousePressed(MouseEvent e) {
if (!isEnabled())
return;
if (e.getClickCount() == 2) {
handleDoubleClick(e);
return;
}
Color color = swatchPanel.getColorForLocation(e.getX(), e.getY());
setSelectedColor(color);
if (tracker != null) {
tracker.addColor(color);
} else {
recentSwatchPanel.setMostRecentColor(color);
}
}
/**
* #param e
*/
private void handleDoubleClick(MouseEvent e) {
if (action != null) {
action.actionPerformed(null);
}
}
}
}
// client code can install the custom panel on a JFileChooser, passing in a tracker
private JColorChooser createChooser(ColorTracker tracker) {
JColorChooser chooser = new JColorChooser();
List<AbstractColorChooserPanel> choosers =
new ArrayList<>(Arrays.asList(chooser.getChooserPanels()));
choosers.remove(0);
MySwatchChooserPanel swatch = new MySwatchChooserPanel();
swatch.setColorTracker(tracker);
swatch.setAction(doubleClickAction);
choosers.add(0, swatch);
chooser.setChooserPanels(choosers.toArray(new AbstractColorChooserPanel[0]));
return chooser;
}
As to doubleClick handling: enhance the swatchChooser to take an action and invoke that action from the mouseListener as appropriate.
You can use the JColorChooser.createDialog method - one of the parameters is a JColorChooser. Use a static instance of the JColorChooser and make it the Dialog modal - that way, only one color chooser is displayed at a time.
The createDialog method also takes ActionListeners as parameters for the OK and Cancel button. Thus, don't really have to manage listeners. Of course, this doesn't persist the recent colors across invocations of the app, just persists recent colors in the current app.
Here's a workaround using reflection - it will work provided the underlying implementation doesn't change. Assuming you have a JColorChooser, add your recent colors to it like this:
final JColorChooser chooser = new JColorChooser(Color.white);
for (AbstractColorChooserPanel p : chooser.getChooserPanels()) {
if (p.getClass().getSimpleName().equals("DefaultSwatchChooserPanel")) {
Field recentPanelField = p.getClass().getDeclaredField("recentSwatchPanel");
recentPanelField.setAccessible(true);
Object recentPanel = recentPanelField.get(p);
Method recentColorMethod = recentPanel.getClass().getMethod("setMostRecentColor", Color.class);
recentColorMethod.setAccessible(true);
recentColorMethod.invoke(recentPanel, Color.BLACK);
recentColorMethod.invoke(recentPanel, Color.RED);
//add more colors as desired
break;
}
}

how to obtain mouse click coordinates outside my window in Java

I need to implement a class, using Swing, which can obtain the mouse coordinates when the user clicks anywhere on the screen. if I wanted to obtain the mouse coordinates inside my own window, I'd use a MouseListener, but I want it to work even when the user clicks outside my program.
I want my class to behave just like KColorChooser: the user clicks on the drop button and he can click anywhere on the screen to obtain the color of that spot. but I don't know if that's possible using pure Java.
It is possible though limited:
Add an AWTEventListener for focus events. As long as your app has focus before the button is clicked you'll receive a focus lost event. Then query for the pointer position.
The limitation is that, of course, your app loses focus. So depending on what you are ultimately trying to achieve this might not be useful.
If you don't want to lose focus then you will have to temporarily take a screenshot of the whole screen and display that in a screen filling window which listens for a mouse click as usual.
Proof of first method:
import java.awt.AWTEvent;
import java.awt.MouseInfo;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import javax.swing.JFrame;
public class Application1 {
public static void main(String[] args) {
Toolkit.getDefaultToolkit().addAWTEventListener(
new Listener(), AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static class Listener implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
System.out.print(MouseInfo.getPointerInfo().getLocation() + " | ");
System.out.println(event);
}
}
}
Clicking outside of the app produced:
java.awt.Point[x=198,y=59] | java.awt.event.MouseEvent[MOUSE_EXITED, ...
java.awt.Point[x=976,y=503] | java.awt.FocusEvent[FOCUS_LOST, ...
The second point is outside of the app.
Forget about GlassPane, there's another 100% native Java way to do it that works both on OS X and on Windows.
Java has always supported translucency for its windows on OS X and Java now supports translucency for its windows on Windows too (since Java 1.6.0_10 or so, needs to be checked).
So the trick is: upon clicking on the "pick a color" tool, you create a nearly transparent borderless Java window covering the entire screen. You set its alpha to 10 (alpha goes from 0 to 255). That alpha is so low the user won't notice that there's a very thin "nearly transparent but only very very very translucent" borderless window covering the entire screen.
Now when the user clicks on your "alpha set to 10 translucent borderless window" covering the entire screen, you get your (x,y).
Discard the borderless Java window.
Use Robot's getRgb(x,y) and you're done.
Why set the alpha to 10 and not 0? Because otherwise clicks aren't intercepted by Java but go directly to the OS (at least that's how it works for a fact on OS X). There's a treshold and I know it's not set at '1', nor '2', it's around 10 or so.
EDIT I just realized you know need to pick several colors, this is trickier but can still be done using 100% Java. Either you can live with "slightly off" colors (affected by the "nearly transparent" 'invisible' layer) or upon getting a click you must remove the layer, get the correct pixel color, and put again a "nearly transparent" layer. Now of course that is one heck of a hack but it can be done in 100% Java.
Use
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
PointerInfo inf = MouseInfo.getPointerInfo();
Point p = inf.getLocation();
p.x and p.y will give you co-ordinates outside your window.
I don't know if that's possible using
pure Java.
Its not possible using pure Java, since Java is only aware of MouseEvents on Windows belonging to Java.
These events are directed to the window which has the focus, from all events on the desktop you can only get the mouse position.
As already shown by Keilly it's only possible to get the mouse postion.
You need to include a native lib
I haven't tried this myself, but maybe you could create a full-screen, transparent panel/frame/etc, and add a MouseListener to that.
It is possible with a little trick. Should be 100% cross-platform (tested on Linux & Windows). Basically, you create a small JWindow, make it "alwaysOnTop" and move it around with the mouse using a timer.
For details, see my answer here.
The location (x,y) and the time interval
(d) between each click is supplied thru command line arguments. Here is the
program
import java.awt.* ;
import java.util.* ;
public final class ClickMouse extends TimerTask {
public static int x, y, d ;
public static void main(String[] args) {
TimerTask clikMouse = new ClickMouse();
Timer t = new Timer();
/*
x = Integer.parseInt(args[0]) ;
y = Integer.parseInt(args[1]) ;
d = Integer.parseInt(ares[2]) ;
*/
x = 500;
y = 200;
d = 5;
t.schedule(clikMouse,1000,d*1000);
}
public void run() {
try
{
Robot bot = new Robot();
bot.mouseMove(x,y);
bot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK );
bot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK);
}
catch (Exception e)
{
System.out.println("Exception occured :" + e.getMessage());
}
}
}
https://github.com/kwhat/jnativehook JNativeHook: Global keyboard and mouse listeners for Java.
I don't have enough rep yet to leave comments, but here are my comments on the other techniques:
Use a native lib: will work, but has obvious distribution limitations
Use GlassPane to fill entire screen: GlassPanes must be contained within a Window.
Create a Window containing a picture of the desktop and fill the entire screen: Will work, but it will suddenly make the desktop static. The cursor will no longer change, any animations or video in other windows or desktop will become eerily static.
Alternative solution:
A refinement of the screen filling window, if you are using Java 6u10 or later is to make the window completely transparent. Put this window in front of all others and listen for mouse clicks. It still has shortcomings, such as no cursor changes, but it depends on what you want to do.
Based on SyntaxT3rr0r's answer I created a sample color picker in groovy which shows how it can work.
import java.awt.*
import java.awt.datatransfer.*
//import com.sun.awt.AWTUtilities;
import javax.swing.WindowConstants as WC;
import javax.swing.SwingConstants as SWC
import groovy.swing.SwingBuilder
class ColorPicker {
SwingBuilder swb = new SwingBuilder()
def window;
def overlayWindow
def mainPanel;
def mainLabel;
def menu;
def transparent = new Color(0, 0, 0, 0);
def nearlyTransparent = new Color(0, 0, 0, 26);
Color color = new Color(150, 150, 255);
def colorHex = { col ->
col = col?: color;
"#"+Integer.toHexString(col.getRGB())[2..-1]
}
def getTextColor = { baseColor ->
baseColor = baseColor?: color;
(baseColor.red*1.5 + baseColor.green*1.5 + baseColor.blue > 400) ? Color.BLACK : Color.WHITE;
}
def setDisplayColor = {newColor ->
mainPanel.background = newColor
mainLabel.foreground = getTextColor(newColor)
mainLabel.text = colorHex(newColor)
}
def show(){
menu = swb.popupMenu { // invoker: mainPanel
menuItem(text: "Pick Color", actionPerformed: capturePixelColor)
menuItem(text: "Copy to Clipboard", actionPerformed: {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(colorHex()), null);
})
separator()
menuItem(text: "Close", actionPerformed: {dispose()})
}
window = swb.frame(
title: "Color Picker",
location:[50,50],
size:[60, 60],
resizable: false,
undecorated: true,
alwaysOnTop: true,
defaultCloseOperation:WC.EXIT_ON_CLOSE
){
def textColor = getTextColor()
mainPanel = panel( constraints: BorderLayout.CENTER,
border: lineBorder(color: Color.BLACK),
componentPopupMenu: menu){
borderLayout()
mainLabel = label(text: "--",
constraints: BorderLayout.CENTER,
horizontalAlignment: SWC.CENTER)
}
}
setDisplayColor(color);
window.show();
}
def capturePixelColor = {
def screenSize = Toolkit.getDefaultToolkit().screenSize
overlayWindow = swb.frame(
location:[0,0],
size: screenSize,
resizable: false,
undecorated: true,
alwaysOnTop: true,
defaultCloseOperation:WC.DISPOSE_ON_CLOSE,
show: true,
background: nearlyTransparent, // AWTUtilities.setWindowOpacity(overlayWindow, 0.1f);
cursor: Cursor.CROSSHAIR_CURSOR,
mouseClicked: {event ->
int x = event.getXOnScreen() // or maybe getX() is enough
int y = event.getYOnScreen()
overlayWindow.dispose()
overlayWindow = null
color = new Robot().getPixelColor(x, y)
setDisplayColor(color)
}
)
}
public static void main(String...args){
println "Welcome to ColorPicker"
def picker = new ColorPicker()
picker.show()
}
}
Look, I understand I am 7 years late...
This is a re-make of Keilly's answer, which allows to get when the mouse button is clicked, anywhere. The main problem is that fullscreen games are always unfocused, and it becomes annoying to handle.
Here is the code:
import java.awt.AWTEvent;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import javax.swing.JFrame;
public class Main {
public static JFrame frame = new JFrame();
public static void main(String[] args) {
Toolkit.getDefaultToolkit().addAWTEventListener(
new Listener(), AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setLocation(1, 1);
}
private static class Listener implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
// We do not want the event to show twice,
// as it shows for focusing and unfocusing
if(event.getID() == 1004) {
Point p = MouseInfo.getPointerInfo().getLocation();
System.out.println("Mouse Clicked at " + p.x + ", " + p.y);
}
// The frame was just unfocused! To make
// sure we get the next mouse click, we
// need to focus it again!
frame.setVisible(true);
}
}
}

Categories