KeyListener doesn't produce any response - java

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.

Related

how to call a keyboard class in main class in java

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).

How can I send a custom key event to an applet?

Basically I have 2 JFrame windows, one of which contains an applet. I am trying to send the key typed to the applet.
#Override
public void keyReleased(KeyEvent e) {
dispatchKeyTyped(e.getID(),e.getModifiers(),e.getKeyCode(),e.getKeyChar(),e.getKeyLocation());
}
#Override
public void keyTyped(KeyEvent e) {
dispatchKeyTyped(e.getID(),e.getModifiers(),e.getKeyCode(),e.getKeyChar(),e.getKeyLocation());
}
public void dispatchKeyTyped(int id, int modifiers, int keycode, char keychar, int keylocation) {
applet.getComponent(0).dispatchEvent(new KeyEvent(applet,id,System.currentTimeMillis(),modifiers,keycode,keychar,keylocation));
}
When I try to do this nothing happens, the key is not send. If I replace the code by sending the KeyEvent like this:
#Override
public void keyReleased(KeyEvent e) {
dispatchKeyTyped(e);
}
#Override
public void keyTyped(KeyEvent e) {
dispatchKeyTyped(e);
}
public void dispatchKeyTyped(KeyEvent event) {
applet.getComponent(0).dispatchEvent(event);
}
This seems to work fine but I want to create the KeyEvent myself and not sure why the first example does not work.

Java why is the key listener not working?

I do not know why this doesn't work. I have already read many posts, and added setFocusable but it just does not work.
public class Spiel {
public static void main(String[] args) {
Playground pg = new Playground();
pg.setLocation(0,0);
pg.setSize(1000,1000);
pg.setVisible(true);
pg.setFocusable(true);
}
}
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Playground extends JFrame implements KeyListener {
Playground(){
}
#Override
public void keyTyped(KeyEvent e) {
System.exit(0);
}
#Override
public void keyPressed(KeyEvent e) {
System.exit(0);
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
You only implemented the KeyListener but if you want it to actually work you still need to register it to your frame.
Playground(){
addKeyListener(this); // should do the trick
}
Otherwise your frame wouldn't know that it actually has to listen and call the methods when a key is pressed.

How to make part of a JTextField uneditable

I wanted to develop a console-like interface, similar to IDLE. That involved determining how to prevent a certain part of the text in a JTextField from being edited. For example:
>>> help
Where the ">>> " is uneditable. The caret must never move behind a certain position, and the text behind that position cannot be edited in any way.
I looked at NavigationFilter, but it doesn't seem to prevent keyboard driven manipulation of the caret.
This shows how to do it with a NavigationFilter:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class NavigationFilterPrefixWithBackspace extends NavigationFilter
{
private int prefixLength;
private Action deletePrevious;
public NavigationFilterPrefixWithBackspace(int prefixLength, JTextComponent component)
{
this.prefixLength = prefixLength;
deletePrevious = component.getActionMap().get("delete-previous");
component.getActionMap().put("delete-previous", new BackspaceAction());
component.setCaretPosition(prefixLength);
}
#Override
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.setDot(Math.max(dot, prefixLength), bias);
}
#Override
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
{
fb.moveDot(Math.max(dot, prefixLength), bias);
}
class BackspaceAction extends AbstractAction
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent component = (JTextComponent)e.getSource();
if (component.getCaretPosition() > prefixLength)
{
deletePrevious.actionPerformed( null );
}
}
}
private static void createAndShowUI()
{
JTextField textField = new JTextField("Prefix_", 20);
textField.setNavigationFilter( new NavigationFilterPrefixWithBackspace(7, textField) );
JFrame frame = new JFrame("Navigation Filter Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Spent a little while figuring this out, so I thought I would share my solution for anyone else with the same dilemma. I don't know if it's optimal, but it does seem to work.
It prevents the user from using backspace behind the postion n. It also moves the caret back to n for any other events, such as (illegally) changing the caret position with the arrow keys or mouse. Finally, it resets the text and caret position after a entry is processed.
EDIT: While I'm leaving this answer here for posterity, see the accepted answer for the best way to solve this problem.
JTextField in = new JTextField();
final String protectMe = ">>> "; //protect this text
final int n = protectMe.length();
in.setText(protectMe);
in.setCaretPosition(n);
in.addCaretListener(new CaretListener()
{
#Override
public void caretUpdate(CaretEvent e)
{
if (e.getDot() < n)
{
if (!(in.getText().length() < n))
in.getCaret().setDot(n);
}
}
});
in.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0)
{
if (in.getCaret().getDot() <= n)
{
in.setText(protectMe + in.getText().substring(n));
arg0.consume();
}
}
#Override
public void keyReleased(KeyEvent arg0){}
#Override
public void keyTyped(KeyEvent arg0){}
});
in.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
String input = in.getText().substring(n).trim();
//do something
in.setText(protectMe);
in.setCaretPosition(n);
}
});
As usual, let me know if there's anything I missed!

keylistener in java not working

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

Categories