Capturing Keystrokes in Java without focus on a Panel - java

I was wondering if there was a way to trigger a KeyEvent with Java's KeyListener while the Java program is running in the background? I want to keep track of what keys are being pressed and save them for later use. Here is a sample of the code I am trying to trigger:
public static class Push implements KeyListener{
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
//Save KeyEvent info here
}
}
I do have a way of saving the information that I want, I just need to trigger this event. I am using an invisible window to cover my screen. I can click through this window , so it gives the appearance of not being there. Any help on this issue would be much appreciated.

Related

Is there a way in swing to capture all keyboard input regardless of focus

The problem
In Swing (Java), I want to capture all keyboard input, regardless of which control has focus.
So, if I press a key on my keyboard (not just alphanumeric, function keys and such included), while the window is in focus, a callback should run, allowing me to do what I want with the given input.
What I've tried
Using the panel I've tried to add a key listener, which implements the KeyListener class in java.awt.event, like so:
// MainApplicationWindow.java
// ...
mPanel.addKeyListener(
new SwingKeyListener()
);
With the actual listener being:
// SwingKeyListener.java
public class SwingKeyListener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {/*...*/}
#Override
public void keyPressed(KeyEvent e) {/*...*/}
#Override
public void keyReleased(KeyEvent e) {/*...*/}
}
Results
GUI is displayed, no errors or exceptions are outputted, key listener does not work.
Solutions
Solution was to use the KeyEventPostProcessor class to poll for input.
KeyEventPostProcessor pp = e -> {
SwingKeyListener.keyPressed(e);
return true;
};
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(pp);

How does this Code show that the Mouse has clicked?

Seen this somewhere in StackOverflow. Just want to know how it works...
public void mouseClicked(MouseEvent e){
int x = e.getX();
int y = e.getY();
}
x and y are coordinates and can be shown to screen using JLabel, but the method name is mouseClicked. How does java know the mouse has been clicked?
(Hope this makes sense)...
The method mouseClicked is likely from java.awt.event.MouseListener interface (https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html)
A listener is a type of callback that follows the observer pattern, something happens, you get notified.
You can attach listener to items that support it. For example:
MouseListener listener = new MouseListener() { /* see example code below */ };
JLabel label = new JLabel("This is a clickable lable");
label.addMouseListener(listener);
See the following answer to get more info and reference to reading articles.
https://stackoverflow.com/a/17415300/132121
#transformer here is an empty implementation of the MouseListener you would create in Java code.
MouseListener listener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
// This is the method where you would get your callback
// whenever somebody clicked on the view that has this listener
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
};
This is an event handler. In order for it to work, it has to be "attached" to something in the front end (most likely a button, but it could be another UI element too).
Exactly how this works depends on which UI framework is being used, but since this is Java I assume it's most likely AWT. You can find more details in tutorials, e.g. here.
Incidentally, how significant the name is depends on which UI framework this is from. In Android, WPF, and ASP.NET, for example, the name of event handlers could theoretically be anything, it's mostly just a matter of convention (not actual requirement) what you call it. (Obviously, you have to be consistent with the name, though). As pointed out in the comments, though, in AWT this name is actually likely significant due to the class that contains it implementing an interface.

Trouble managing keyboard focus

I'm currently working on an application that generates a kenken puzzle, wherein the user inputs number to solve it. However, I can't seem to get the focus system to work; my JFrame doesn't even receive focus to begin with. Here is the method which initializes the main frame:
public static void initMain() {
mainframe.setVisible(true);
mainframe.setSize(new Dimension(900, 900));
mainframe.requestFocus();
System.out.println(mainframe.isFocusOwner());
System.out.println(mainframe.isFocusable());
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainframe.setContentPane(puzzle);
in = mainframe.getInsets();
mainframe.setJMenuBar(bar);
bar.add(menu);
menu.add(item);
item.addMouseListener(new MouseListener () {
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {popup();}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
});
}
(latter half not so important here, just showing it for completions's sake)
The first output is always false, and key events aren't generated. From what I gethered online, setting the window to visible and requesting focus should be enough, although the emphasis is on should. My operating system is Windows 8, incase that makes a difference.
Ok nvm, got the focus to work via requestFocusInWindow (which also didn't work previously). Seems like the problem was requesting focus too early and only once. Why the mainframe focus didn't work either I still don't quite get, but that doesn't matter now I guess. Thanks anyways for your answers.

How to catch mouse motion event in some ceratin area of a component?

I use a Jlayered pane with 4 layers and put in each layer a colored label to distinguish one from another. The layers do not completely overlap. I want each time the mouse move to a layer, something happens like the layer change color. How I can make my program detect which layer the mouse is on and react accordingly?
Assuming you are using Swing, if each layer is a panel or some other kind of swing component, you can add a MouseListener to the panel or layer.
// Add a MouseListener to every individual layer
layer.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
// This method will be fired each time the mouse enters the layer
// So any code here will execute when the mouse enters said layer
// Which means you could put code here to change the color, etc.
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
});
If you want more information on the topic, you can read a tutorial on how to write a MouseListener from Oracle. https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
Or even watch a video on how to create a MouseListener. https://www.youtube.com/watch?v=MpIHF4V3zMc

Ignoring Java mouse events on AWT components that were generated from lightweight components

I have a JFileChooser that is opened on top of an AWT component (we use a GLCanvas for some openGL rendering). If I double click the icon in the file chooser to close it, the mouse clicks are passed to the GLCanvas. I have read that mouse events on the lightweight components will be passed to the heavyweight components, but is there a way to detect when this is happening? Double clicking on the GLCanvas performs another operation, which I would prefer not happen when the user is just double clicking to close the dialog.
You could create event handlers for the mouse events on the lightweight components and then do nothing inside of them, that should stop the propagation to the heavier components.
Something like:
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}

Categories

Resources