I have been trying to increment a variable every time the space bar is pressed in Java.
The code I wrote is below but it seems to be wrong as it increments without pressing the key.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TestKeyPress {
public static void main(String[] args) {
System.out.println(keyPressed(null));
}
public static int keyPressed(KeyEvent e) {
int var = 0;
while (var <6) {
var ++;
System.out.println(hi);
}
System.out.println("max reached");
return var;
}
}
You need to bind the listener into an event. You cannot expect anything happens when the passed KeyEvent
is null
. Moreover, you don't specify anywhere the space bar is pressed. You also miss the context to which is the key-press event registered. Is it a console or a desktop application? As long as you use java.awt.event
I suspect the latter. Here is a minimal sample:
Java Desktop application using Swing
public static void main(String[] argv) {
JTextField textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
int counter = 0;
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
if (counter < 6) {
counter++;
System.out.println("hi");
} else {
System.out.println("max reached");
}
}
}
});
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(640, 320);
jframe.setVisible(true);
}
Console application
In that case, you cannot use anything from the java.awt.*
or javax.swing.*
libraries and you have to stick with classes from java.io.*
.
Because when the keyPressed
called the var variable will be zero, you should declare outside the keyPressed
.
Also if you want to bind with the progress bar you should implement the listener.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TestKeyPress {
private static int var = 0;
public static void main(String[] args) {
System.out.println(keyPressed(null));
}
public static int keyPressed(KeyEvent e) {
while (var < 6) {
var ++;
System.out.println(hi);
}
System.out.println("max reached");
return var;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.