Detecting MouseClicks without JFrame - java

Currently stuck on how to create an executable jar file that would run in the background of my pc and detect if my mouse is down. I know JFrame is a one method of doing so, but that's visible on my screen, even though I set it to invisible it appears to disable it completely.
Here's my code so far, is there a another method I could use that isn't JFrame related?
public class MyFrame extends JFrame implements KeyListener {
MyFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
this.setLayout(null);
this.addKeyListener(this);
this.setVisible(true);
this.setAlwaysOnTop(true);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() =='q'){
this.setVisible(false);
}
if(e.getKeyChar()=='l'){
this.setVisible(true);
}
}
}

You can download jNativeHook and hook the global listener to globalScreen.
you can use it as a normal swing listener.
Here is the link:
https://code.google.com/p/jnativehook/
By using this library you achieve a wide range of functions to control the mouse events!!

Related

MouseEvents are Captured but not KeyEvents Java JComponant

I'm working on an old game project called Lemmings, and the Principle Game Panel is working well and receiving the MouseEvents but not the KeyEvents, which is not very logic for me, so I copied down the Code of this file for you guys to see whats going on.
The GamePanel class extends JComponent SWING class
public class GameFrame {
private class GamePanel extends JComponent {
GamePanel(Dimension dim) {
setPreferredSize(dim);
//first version of the question was with the keyListner
/*addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println(e.getKeyCode());
//nothing show up
}
});*/
//I tried using this, but it didn't work
//getInputMap().put(KeyStroke.getKeyStroke("A"), "action");
// this works cause we use the right inputMap not the one by default
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("A"), "action");
getActionMap().put("action",new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("A is pressed");
//now it works
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println(e.getPoint());
}
});
setVisible(true);
}
}
private JFrame window;
private GamePanel panel;
public GameFrame() {
window = new JFrame("Test");
window.setLocationRelativeTo(null);
panel = new GamePanel(new Dimension(400, 400));
window.setContentPane(panel);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public static void main(String[] args) {
new GameFrame();
}
}
UPDATE WITH SOLUTION
I learned that JComponants are not focusable and so it doesn't receive KeyEvents so we have to use the Key Bindings method
I found out that every JComponent has three inputMaps referred to by WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT and we have to make sure that we are using the right one for our work
for more informations look on How to use key Bindings and check the methods getInputMap() and getInputMap(int)
Key events are only dispatch to a focusable component.
By default a JPanel is not focusable so it does not receive key events.
If you are attempting to invoke some kind of Action based on a KeyEvent then you should be using Key Bindings, not a KeyListener. A key binding will allow you to listen for a KeyStroke even if the component doesn't have focus.
Read the section from the Swing tutorial on How to Use Key Bindings for more information and working examples.
the problem can be solved simply by adding a KeyListener to the JFrame in case we don't need to create Actions and stuff
this solution can only be possible if there are no other components focusable.
in the file GameFrame.java
in the function void init();
add
window.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed (KeyEvent e) {
super.keyPressed(e);
System.out.println("test "+e.getKeyChar());
}
});

JRootpane - setting glasspane to visible doesnt intercept mouse events

I have a JFrame and a JPanel hierarchy inside it, i want to implement an inner panel that i can make it look "disabled"(while other panels dont change), that is, to cover it by a semi transparent gray layer and intercept all mouse and perhaps even keyboard events that are dispatched to this panel. ive been searching for a solution and didnt really find a good one yet.
The closest i got to a solution was when i used JRootPane, whenever i want it disabled i make its glasspane visible. the glasspane had been set to be opaque and with semi transparent background.
A simple example of my attempt :
public class Test extends JFrame {
private final JPanel jPanel;
public Test() {
jPanel = new JPanel();
final JButton jButton = new JButton("Hidden");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("hidden is clicked!");
}
});
final JRootPane jRootPane = new JRootPane();
jPanel.add(jRootPane);
final JPanel glassPane = new JPanel();
final JButton jButton2 = new JButton();
jButton2.addActionListener(new ActionListener() {
private boolean visible = true;
#Override
public void actionPerformed(ActionEvent e) {
glassPane.setVisible(visible = !visible);
}
});
jPanel.add(jButton2);
jRootPane.getContentPane().add(new JScrollPane(jButton));
glassPane.setBackground(new Color(0.5f, 0.5f, 0.5f, 0.2f));
glassPane.setOpaque(true);
jRootPane.setGlassPane(glassPane);
glassPane.setVisible(true);
getContentPane().add(jPanel);
}
public static void main(String[] strings) {
final Test test = new Test();
test.pack();
test.setVisible(true);
}
}
But the problem is that even when the glass is visible on top of the content, it doesnt intercepts events from getting to the content as it should, as documented here.
In your test class your glasspane doesn't intercept events, because you didn't tell it to intercept events (intercepting events is not a default behavior).
In the documentation link, it says
The glass pane
The glass pane is useful when you want to be able to catch events or paint over an area that already contains one or more components. For example, you can deactivate mouse events for a multi-component region by having the glass pane intercept the events. Or you can display an image over multiple components using the glass pane.
You can intercept Mouse Events this way:
glassPane.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
e.consume();
}
#Override
public void mousePressed(MouseEvent e)
{
e.consume();
}
});
You can intercept KeyBoard Events this way:
glassPane.setFocusable(true);
glassPane.addKeyListener(new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
e.consume();
}
#Override
public void keyReleased(KeyEvent e)
{
e.consume();
}
#Override
public void keyPressed(KeyEvent e)
{
e.consume();
}
});
Note: The JPanel has to be focasable to intercept the keyboard events.

repaint of main panel not working properly when using an internal frame

I'm having the following bug/problem and I havent been able to found solution yet on web or example of someone with similar issue.Basicaly I have a main frame that contains a panel of the same size(acting as the main panel) and When you press "Enter" an internal frame pop up(on top of where the playersprite is) acting as the inventory and then the control is passed to it and if you press "Enter" again the inventory is destroyed and control is passed back to the main panel.
the repaint function is called and the character and the map is then redrawn and this work about 90% of the time.The other 10% or less of time whenever the inventory is destroyed it seems the repaint is called(and work) except nothing is drawn its as if it draw on the destroyed panel because if I add a debug keypress that call repaint on the mainpanel(thescreen) everything is back to normal.
of course I could just repaint the character every loop in the run() method but thats terrible since I will only repaint if something changed(ie I moved)
I removed all the move and other code since they arent useful and still get the problem with the below code.You can think of the Character class as a plain drawn square.Anyone as any insight on why this is happening?
public class main extends JFrame implements Runnable{
private boolean gameRunning=true;
private Character Link;
private MainScreen theScreen;
public final int ScreenHeight=500;
public final int ScreenWidth=500;
public boolean inMenu=false;
Block ablock=new Block(200,200);
public class Inventory extends JInternalFrame{
public Inventory(){
setBounds(25,25,300,300);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setVisible(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
int key=e.getKeyCode();
if(key==KeyEvent.VK_ENTER){
try{
setClosed(true);
theScreen.requestFocusInWindow();
theScreen.repaint();
inMenu=false;
}
catch(Exception ex){}
}
}});
}
}
class MainScreen extends JPanel{
MainScreen(){
super();
setIgnoreRepaint(true);
setFocusable(true);
setBounds(0,0,ScreenWidth,ScreenHeight);
setVisible(true);
setBackground(Color.white);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Link.draw(g);
g.drawImage(ablock.getImg(),ablock.getX(), ablock.getY(),null);
}
}
main(){
super();
final JDesktopPane desk = new JDesktopPane();
theScreen=new MainScreen();
add(theScreen);
theScreen.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
int key=e.getKeyCode();
if(key==KeyEvent.VK_ENTER){
inMenu=true;
Inventory myInventory=new Inventory();
desk.add(myInventory);
myInventory.requestFocusInWindow();
}
}
});
add(desk);
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {}
setTitle("Project X");
setResizable(false);
Link=new Character();
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
main Game=new main();
new Thread(Game).start();
}
public void run(){
//omitted/irrelevant only contains a FPS count
}
}
}
Don't use KeyListeners. Use Key Bindings.
Don't use a Thread. Use a Swing Timer for animation so updates will be done on the EDT.
Don't use an Internal Frame for a popup window. Use a JDialog.
Do custom painting on a JPanel, not a JDesktopPane.
Don't use setIgnoreRepaints(). That is used for active rendering.
Don't use empty catch clauses.
Use standard Java naming conventions. Classes start with upper cases characters, variable names do not.
Don't use setBounds(). Use a Layout Manager.

JPanel doesn't response to KeyListener event

I have a subclass of JFrame that uses a class extended from JPanel
public class HelloWorld extends JPanel implements KeyListener
I add an object of HelloWorld to the frame - app.add(helloWorld);. Now, when I press any keyboard key non of the KeyListener methods gets called and it seems that helloWorld doesn't have window focus. I have tried also to invoke helloWorld.requestFocusInWindow(); but still doesn't respond.
How can I make it respond to key press?
Did you set that KeyListener for your HelloWorld panel would be that panel itself? Also you probably need to set that panel focusable. I tested it by this code and it seems to work as it should
class HelloWorld extends JPanel implements KeyListener{
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped: "+e);
}
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed: "+e);
}
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased: "+e);
}
}
class MyFrame extends JFrame {
public MyFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200,200);
HelloWorld helloWorld=new HelloWorld();
helloWorld.addKeyListener(helloWorld);
helloWorld.setFocusable(true);
add(helloWorld);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
JPanel is not Focusable by default. That is, it can not respond to focus related events, meaning that it can not respond to the keyevents.
I would suggest trying to setFocusable on the pane to true and trying again. Make sure you click the panel first to make sure it receives focus.
Understand though, you WILL get strange focus traversal issues, as the panel will now receive input focus as the user navigates through your forms, making it seem like the focus has been lost some where.
Also, KeyListeners tend to be unreliable in this kind of situation (due to the way that the focus manager works).
simple you have to add
addKeylistener(new HelloWorld());
add this in MyFrame method;
HelloWorld() helloWorld = new HelloWorld();
this.addKeyListener(helloWorld);

KeyListener not being triggered after I swap JPanels

Im making a game and Im having it so that when the user presses "I" in the game, the game panel is set to invisible while it adds the Inventory panel to the JFrame. Then when the user exits the Inventory it will remove the Inventory JPanel and then set back the game JPanel to visible.
Now this all sounds good, but whenever it removes the Inventory JPanel and goes back to the game JPanel, the KeyListener stops working. I even set back the setFocusable(true) property back on the game JPanel after I remove the Inventory JPanel but it still doesn't make the KeyListener work.
Here is my code for the game Jpanel:
package javavideogame;
public class Game extends JPanel implements ActionListener, Runnable
{
public Game(MainCharacter character)
{
TAdapter a = new TAdapter();
addKeyListener(a);
setFocusable(true);
setDoubleBuffered(true);
setFocusTraversalKeysEnabled(false);
}
public void getInventoryScreen()
{
Main.inv = new Inventory();
Main.inv.sayHello();
Main.mainGame.getContentPane().add(Main.inv);
Main.game.setVisible(false);
Main.mainGame.validate();
}
public void closeInventory()
{
Main.inv.setFocusable(false);
Main.mainGame.remove(Main.inv);
Main.game.setVisible(true);
Main.game.setFocusable(true);
}
public class TAdapter extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
character.keyPressed(e);
}
public void keyReleased(KeyEvent e)
{
character.keyReleased(e);
}
}
}
And here is the Inventory code:
package javavideogame;
public class Inventory extends JPanel implements KeyListener
{
public Inventory()
{
setBackground(Color.RED);
addKeyListener(this);
setFocusable(true);
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_I)
{
Main.game.closeInventory();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
And yes im having a hard time getting the code thing on here to work right :)
But is there something i can easily put into the code so that the KeyListener will actually work right once it goes back to the game JPanel?
I even set back the setFocusable(true) property back on the game JPanel after I remove the Inventory JPanel
Key events only go the the component that has focus. You need to invoke:
panel.requestFocusInWindow();
after swapping the panels to make sure the panel has focus again.
However, a better approach is to use Key Bindings itead of a KeyListener.
You could skip working with adding and removing panels to the content pane and just set the visibility. Then you should also skip setting the focusable property (KeyEvents won't be passed to an invisible component anyway) and your key listeners should be preserved and come into effect again when the component becomes visible.

Categories

Resources