I want my java program to be running in the background by default, but use a keylistener to call my changewallpaper class. The changewallpaper class definently works, but the keylistener does not call the method. The keyevent will be changed later it's currently just for testing.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class listener implements KeyListener {
public static void main(String[] args){
}
#Override
public void keyReleased(KeyEvent arg0) {
int key = arg0.getKeyCode();
if (key == KeyEvent.VK_UP) {
changewallpaper.main();
}
}
#Override
public void keyTyped(KeyEvent arg0) {
int key = arg0.getKeyCode();
if (key == KeyEvent.VK_UP) {
changewallpaper.main();
}
}
#Override
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
if (key == KeyEvent.VK_UP) {
changewallpaper.main();
}
}
}
A KeyListener does not listen to all keyboard events indiscriminately - it only listens to events on a particular Component, when that Component has keyboard focus. You have to attach the listener to something with an addKeyListener method or similar.
See the Java How to Write a Key Listener tutorial
Related
Not sure if I asked the question right but I am using keylistener for keyboard inputs in keyboard.java. I want to call the keyboard.java file in the display.java (main class) so that when I run the display class, I press a key and print something out to test it. Here is the code for the keyboard.java file:
public class Keyboard implements KeyListener {
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
if(key == KeyEvent.VK_E) {
System.out.println("E pressed");
}
}
#Override
public void keyReleased(KeyEvent event) {
}
}
I already typed in private Keyboard keyboard; into the display class but nothing is happening when I press the E key. I need help and I am using Eclipse (Im new to java).
We areto create a plane and have its speed increase 5mph every time the user inputs the up arrow key and decrease 9mph when hitting the down key. It is supposed it report this back to the user in output box whenever whichever action is completed. How do I set it up so that the keylistener will tell the user that they have pressed the up key? Im still working on this so sorry if it is messy.
private class PolygonPanel implements MouseListener, MouseMotionListener, KeyListener
{
public void mousePressed(MouseEvent event){} //unused event
public void mouseDragged(MouseEvent event){} //unused event
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){}
//public void keyPressed(KeyEvent event){}
public void keyPressed(KeyEvent event) {
Integer planespeed=event.getKeyCode();
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
//Not gonna use this.
}
if (event.getKeyCode() == 39)//KeyEvent.VK_LEFT
{
System.out.print("This key is up");
}
if (event.getKeyCode() == KeyEvent.VK_UP)
{
System.out.print("This key has been pressed");
//speed=planespeed+5;
}
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
//speed=planespeed-9;
}
repaint();
}
A frame doesn't detect keybaord input if it is not focused on. Therefore, in order to retrieve keyboard input of any kind, you would have to set your frame to be focusable, using a line such as setFocusable(true); in your constructor. You might also have to add a line such as addKeyListener(new PolygonPanel()); so the listener is registered at all.
Given the following (partial) code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Test extends Applet implements MouseListener , KeyListener
{
private static final long serialVersionUID = 1L;
private static final int TOTAL_POINTS = 500;
private static final int THRESHOLD = 5;
// the arrays that contain the indexes of the points that the user created
private int[] m_Xindex, m_yIndex;
// The number of points that the user created
private int m_pointsCreated;
#Override
public void keyTyped(KeyEvent keyEvent)
{
char key = keyEvent.getKeyChar();
if (key == 'F')
System.out.println("123");
}
#Override
public void mouseReleased(MouseEvent arg0) {/* Empty */ }
#Override
public void mouseClicked(MouseEvent e) {/* Empty */ }
#Override
public void mouseEntered(MouseEvent e) {/* Empty */ }
#Override
public void mouseExited(MouseEvent e) {/* Empty */ }
#Override
public void mousePressed(MouseEvent myEvent) {/* Empty */ }
#Override
public void keyPressed(KeyEvent keyEvent) {}
#Override
public void keyReleased(KeyEvent keyEvent) {}
}
I removed my working code and left only the problematic code.
When I press F , I want to print to the screen 123 , but nothing is
printed to the screen.
What's wrong with the code of keyTyped?
Change if (key == 'F') to if (key.equals('F')). Test for object equivalence rather than equality.
Be sure that the component is focusable & to requestFocusInWindow(). The latter should best be done by an #Override on the start() method.
Consider using Swing (JApplet) and key bindings instead of AWT Applet and KeyListener.
I am currently trying to implement a keylistener in my program so that it does an action when I pressed an arrow key, the object in my program either moves left or right.
Here is the moving method in my program
public void moveDirection(KeyEvent e)
{
int move = 0;
int r = K.getRow();
int c = K.getCol();
if (e.getKeyCode() == 39) move = 1; //KeyEvent.VK_RIGHT
if (e.getKeyCode() == 37) move = 2; //KeyEvent.VK_LEFT
//if (e.getKeyCode() == KeyEvent.VK_DOWN) move = 3;
switch (move)
{
case 1: if (inBound(r, c+1))
K.setLocation(r ,c+1);
if (inBound(r, c-1) && frame2[r][c-1] == K)
frame2[K.getRow()][K.getCol()-1] = null;
break; //move right 39
case 2: K.setLocation(K.getRow(), K.getCol()-1); break; //move left 37
//case 3: b.setLocation(b.getRow()+1, b.getCol()); break; //move down
default: return;
}
processBlockList();
}
I am wondering how the program is supposed to read in (KeyEvent) e. I cannot really type in an arrowkey....
Please help!
edit: I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Check this tutorial
If it's a UI based application , then " I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method" you can use GlassPane or Timer class to fulfill the requirement.
For key Event:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/
Here is an SSCCE,
package experiment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyListenerTester extends JFrame implements KeyListener {
JLabel label;
public KeyListenerTester(String s) {
super(s);
JPanel p = new JPanel();
label = new JLabel("Key Listener!");
p.add(label);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key typed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key typed");
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings
The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So
Make one Key listener class as
class MyListener implements KeyListener{
// override all the methods of KeyListener interface.
}
Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.
Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.
JFrame f=new JFrame();
f.addKeyListener(new MyKeyListener);
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
#Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.
Ok, how to i move from keyboard a ball using an Applet?
I have so far this code, that don't do anything.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class KeyboardGame extends Applet implements KeyListener
{
private static final long serialVersionUID = 1L;
private static boolean keyboadrRightPressed = false;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboadrRightPressed = true;
}
else
{
keyboadrRightPressed = false;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void paint(Graphics g)
{
g.fillOval(20,20,20,20);
g.drawString("String :"+keyboadrRightPressed,20,30);
}
}
And also i have to understand how it works. I don't get why my action listener won't work, do i need an
while(true)
or an Thread?
Your action listener might actually be working fine, but you need to repaint the applet when the key is pressed so that your string actually appears. Try changing the keyPressed to this:
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboadrRightPressed = true;
}
else
{
keyboadrRightPressed = false;
}
repaint();
}
Actually moving the ball will differ depending on how you want the ball to actually move. I'm guessing you want it to continue moving right while the key is held down, so what I would do is implement a timer or some other form of thread that every .25 seconds (or however long you want) checks the keyboardRightPressed and will move the ball right if it is true. Then in the keyReleased portion of your code you should also add logic to set keyboardRightPressed back to false when you let up on the key.