I have looked at a bunch of answers to a previous question I had (it was answered), but something that I kept seeing were methods like:
public void keyPressed(KeyEvent e)
but none ever showed where these methods were used, so I never figured out what to do with the argument.
Example:
public void keyPressed(KeyEvent e, Robot r) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
r.keyPress(KeyEvent.VK_R);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception s) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
public static void autoCliker() throws AWTException, InterruptedException
{
Robot r = new Robot();
while(KeyPressed(not sure what to do here, r)//this is what my question is about
{
Thread.sleep(10);
r.keyPress(KeyEvent.VK_R);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception e) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
It's more about how to use an Event in an argument within a method than about the KeyEvent, I am just using one of my programs as an example.
This method, along with others, shows up when your class implements KeyListener.
public class Test implements KeyListener {
This method senses key's pressed on the keyboard. If you want to detect a certain key like w. Do this:
if(e.getKeyCode.equals(KeyEvent.VK_W);
Hope this helps.
Related
So basically i tried to get this while loop to run inside this thread, it should activate when "activate" evaluates to true but for some reason it is not working.
"activate" is boolean value which activates when user presses mouse button (i setted up listener for that). If anyone wonders im using jnativehook library for this project. Any help or explanation would be greatly appreciated.
private boolean activate;
private Robot robot;
#Override
public void run() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while(true) {
if (activate == true) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
}
}
}
activate is never set to true.
If you don't believe me then add this line at the bottom of your while loop:
System.out.println("activate = " + activate);
One possibility is that the compiler (either the Java compiler, or the JIT compiler) has decided that it does not need to test activate because it can prove that nothing inside the while loop ever changes it. In most compiled programming languages, the compiler is allowed to assume that the code will be single threaded unless you do something special to tell it otherwise. That assumption is justified because it enables the compiler to generate much more efficient code most of the time.
Accessing the variable from within a synchronized block, or declaring the variable to be volatile would prevent the compiler from making that assumption.
Better still would be to use a private final AtomicBoolean activate;.
// Here is the sample program which should run your method correctly. All the changes
// are commented upon. Don't judge harshly, not a professional with java
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.util.Scanner;
class Processor extends Thread {
// Have to initialize the variable here
private boolean activate = true;
private Robot robot;
public void run() {
try {
robot = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// No need for while (true) here
while (activate) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
}
}
// method to stop the program
public void shutdown() {
activate = false;
}
}
public class App {
public static void main(String[] args) throws AWTException, InterruptedException, NullPointerException {
// activates the process
Processor p = new Processor();
p.start();
// Press any key to stop the process
// program will run endlessly until scanner value (key input) is provided
Scanner key_input = new Scanner(System.in);
key_input.nextLine();
p.shutdown();
}
}
Thanks for all suggestion fixed the problem by passing class instance to my MouseListener class.
For anyone that gets same problem:
public boolean activate;
public boolean toggled;
private Robot robot;
public MouseListener mouseListener = new MouseListener();
public KeyboardListener keyListener = new KeyboardListener();
public static Game instance;
public Game() {
this.activate = false;
// this.toggled = false;
try {
GlobalScreen.registerNativeHook();
GlobalScreen.isNativeHookRegistered();
GlobalScreen.addNativeMouseListener(mouseListener);
GlobalScreen.addNativeKeyListener(keyListener);
} catch (NativeHookException e) {
e.printStackTrace();
}
}
public void run() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while(true) {
try {
Thread.sleep(1L);
if(Game.this.isActivate()) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean isActivate() {
return activate;
}
public void setActivate(boolean activate) {
this.activate = activate;
}
public boolean isToggled() {
return toggled;
}
public void setToggled(boolean toggled) {
this.toggled = toggled;
}
**public static Game getGame() {
if(Game.instance == null) {
Game.instance = new Game();
}
return Game.instance;
}**
Here is the class that changes "activate" to "true".
public void nativeMouseClicked(NativeMouseEvent e) {
// nothing
}
public void nativeMousePressed(NativeMouseEvent e) {
if(e.getButton() == NativeMouseEvent.BUTTON1) {
Game.getGame().setActivate(true);
}
}
public void nativeMouseReleased(NativeMouseEvent e) {
if(e.getButton() == NativeMouseEvent.BUTTON1) {
Game.getGame().setActivate(false);
}
}
}
I would like to ask about a problem i encountered while trying to make a method which can read text from a file.
For example, I created a simple interface, when you click the buttons, the text with a predefined folder path will be read.
So i use actionListener like this. Note that "einlesen" is "read" in German.
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == einlesenDatei)
{
this.einlesen();
}
if (source == decoder)
{
this.decode();
}
}
The problem is, the readInput method required me to throw a FileNotFoundException, and the actionPerformed method requires me to cut off the throw exception part.
You can put the code for read method in a try catch block like this:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == inputFile) {
try {
this.readInput();
} catch (FileNotFoundException e) {
// handle the exception
}
}
if (source == decoder) {
this.decode();
}
}
I am trying to implement key loggers in java using Jnative hook.I 'm able to record every key movement.This is the output which i am able to get till now
When i'm trying to type "facebook" this is how it is recording
f
a
c
e
b
o
o
k
But i want it to print it like a single word like every other keylogger does.
which means when i enter something like facebook.it should record it as "facebook" but not like recording every keyboard char.
Below posted is my code:
public class key_logger implements NativeKeyListener {
#Override
public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
System.out.print(nativeKeyEvent.getKeyChar());
if(nativeKeyEvent.getKeyCode()== NativeKeyEvent.VK_ESCAPE)
{
//System.out.println("Ter");
GlobalScreen.unregisterNativeHook();
}
}
#Override
public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {
}
#Override
public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
System.out.println(nativeKeyEvent.getKeyChar());
}
public static void main(String[] args)
{
try
{
GlobalScreen.registerNativeHook();
} catch (NativeHookException e) {
System.out.println("There is a problem registering with the hook");
e.printStackTrace();
System.exit(1);
}
GlobalScreen.getInstance().addNativeKeyListener(new key_logger());
}
}
Store the characters in a String and whenever you come across enter or spacebar being pressed just print the String make sure to reinitialize the String
String string ="";
#Override
public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
string.append(nativeKeyEvent.getKeyChar());
if(nativeKeyEvent.getKeyCode()=='key code for enter' && nativeKeyEvent.getKeyCode()== 'key code for space'){
System.out.println(string);
string="";
}
}
I have a problem with creating an outputstream file.
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
It worked fine, until I made another method:
public void actionPerformed (ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
Previously, I put throws Exception at the start of each method that calls upon the
createprofile();
method (in which the output stream is). But now I get
ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
^
overridden method does not throw Exception
Previously, I was wondering if there was another way to throw the exception: cannot implement actionPerformed(ActionEvent) in ActionListener
But now I think that it would be better to somehow force the outputstream to make the file. I have googled multiple phrasings of this, but I do now know how to do this... the things I found did not work either.
The ActionListener interface does not declare it's actionPerformed method as throwing any type of Exception, you can not change this signature.
You need to catch and manage the exception from within the method.
public void actionPerformed(ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn) {
menu.setVisible(false);
try {
createProfile();
} catch (Exception exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE);
}
menu.setVisible(true);
} else {
//...
}
}
FileOutputStream is capable of creating the file if it does not exist, but may have issues if the path doesn't or if you don't have adequate permissions to write to the specified location or any number of other possible issues...
You're getting a type mismatch. The ActionListener interface's actionPerformed method does not include a throws Exception clause, therefore you can't include one on the method you override. A simple fix is to catch any Exception thrown, and re-throw it as a RuntimeException. Since RuntimeExceptions are unchecked, you don't need to include it in the throws clause.
public void actionPerformed (ActionEvent e) //When a button is clicked
{
try { // <-- Added try block
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
catch (Exception e) { // <-- Catch exception
throw new RuntimeException(e); // <-- Re-throw as RuntimeException
}
}
It's usually better to actually handle the exception if possible, but if you just want to see the exception (e.g. for debugging), then I'd say wrapping it in a RuntimeException and re-throwing it is a little cleaner than just adding throws Exception on the end of all your method signatures. It's also better if you can narrow the type of Exception in the catch block down to the actual exception types you're expecting.
I have run into a curious issue. I need to export some text to a file as a result of pressing a button in a GUI. I cannot, however, apply an IOException to the actionPerformed method of the AbstractAction that is called by the event. I am at a loss as to how to get around this.
Here is the export class:
import java.awt.event.*;
import java.lang.*;
import java.util.*;
import java.io.*;
public class ExportRunner
{
public static void exportToFile(ArrayList<Locker> list) throws IOException
{
}
}
And the AbstractAction extension:
class Export extends AbstractAction
{
public Export()
{
super("Export");
}
public void actionPerformed(ActionEvent e)
{
ExportRunner.exportToFile(list);
}
}
First of all are you sure you want to re throw the exception or maybe is better to handle it and/or show a message to the user?
Option 1: re-throw the exception (ugly in my opinion):
public void actionPerformed(ActionEvent e) {
try{
ExportRunner.exportToFile(list);
} catch(IOException ioex) {
throw new RuntimeException(ioex);
}
}
Option 2: catch and handle it:
public void actionPerformed(ActionEvent e) {
try{
ExportRunner.exportToFile(list);
} catch(IOException ioex) {
handleItOrShowMessageToUser(ioex);
}
}
I would normally pass in a "error handler" to the action class that would allow the delegation of the responsibility of dealing with showing/reporting the error to another part of the application...
Something like...
public interface ErrorListener {
public void errorOccurred(String msg, Exception exp);
}
Then you could pass it to you action...
public class Export extends AbstractAction
{
private ErrorListener errorHandler;
public Export(ErrorListener errorHandler)
{
super("Export");
this.errorHandler = errorHandler;
}
public void actionPerformed(ActionEvent e)
{
try {
ExportRunner.exportToFile(list);
} catch (IOException exp) {
errorHandler.errorOccurred("Failed to export file", exp);
}
}
}
Obviously, somewhere, you need a implementation to handle the callback ;)
You might like to have a look at the Exception trail for more information