How to check KeyListener input? - java

In java.awt.event.KeyListener, how do I check if the user enters "+" or "- "?

Here's a code example of how to do this:
TextField field = new TextField();
field.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
final char aChar = e.getKeyChar();
if (aChar == '+') {
System.out.println("+ was typed");
}
if (aChar == '-') {
System.out.println("- was typed");
}
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
});

Related

Howto modify java-code from single to simultaneous key press? [duplicate]

I need an example how to add a keyboard handler that detect when Ctrl+C , Ctrl+X , Ctrl+C pressed on a JTree.
I were do this before with menu shortcut keys but with no success.
You can add KeyListeners to any component (f)
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use KeyListener for example :
jTree1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_C) {
JOptionPane.showMessageDialog(this, "ctrl + c");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_X) {
JOptionPane.showMessageDialog(this, "ctrl + x");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
JOptionPane.showMessageDialog(this, "ctrl + v");
}
}
});
Hope that helps.
Use Key Bindings.
initComponents();
KeyboardFocusManager ky=KeyboardFocusManager.getCurrentKeyboardFocusManager();
ky.addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID()==KeyEvent.KEY_RELEASED && (e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("Dhanushka Tharindu");
}
return true;
}
});
But menu shortcut accelerators are the way to do this normally: myMenuItem.setAccelerator(KeyStroke.getKeyStroke("control C"));

JTextField only 13 or 17 digit valid and all invalid except (13 and 17)

Currently I'm using this code but it's not working properly , when i remove 1 or 2 or 3 digit out of 17 but success icon still visible.
#Override
public void keyReleased(KeyEvent e) {
if(Strings.isNullOrEmpty(txtVID.getText())){
lblIDValidation.setIcon(null);
isVIDValid= false;
}
}
#Override
public void keyPressed(KeyEvent e) {
if(txtVID.getText().length()==16 || txtVID.getText().length()==12 || txtVID.getText().length()==17){
lblIDValidation.setIcon(createImageIcon(CommonUtil.success));
isVIDValid= true;
return;
}
lblIDValidation.setIcon(createImageIcon(CommonUtil.danger));
isVIDValid= false;
}
A KeyListener is a poor choice, generally, but espcially for text components, apart from not guaranteeing the order in which key events might be delivered to your listener, which could change the behavior on different platforms, they don't take into account what happens when you use setText or the user pastes text into the field.
A better choice is to use a DocumentListener, for example
JTextField field = new JTextField(20);
field.getDocument().addDocumentListener(new DocumentListener() {
public void verify() {
int length = field.getText().trim().length();
if (length >= 16 && length <= 17) {
field.setBackground(null);
} else {
field.setBackground(Color.RED);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
verify();
}
#Override
public void removeUpdate(DocumentEvent e) {
verify();
}
#Override
public void changedUpdate(DocumentEvent e) {
verify();
}
});
field.setText(" ");
field.setText(null);
See Listening for Changes on a Document for more details
Now it's working fine....If anyone have problem to use this code just comment below.
lblIDValidation.setIcon(null);
txtVID.getDocument().addDocumentListener(new DocumentListener() {
public void verify() {
int length = txtVID.getText().trim().length();
if (length == 17 || length == 13) {
lblIDValidation.setIcon(createImageIcon(CommonUtil.success));
isVIDValid= true;
} else {
lblIDValidation.setIcon(createImageIcon(CommonUtil.danger));
isVIDValid= false;
}
}
#Override
public void insertUpdate(DocumentEvent e) {
verify();
}
#Override
public void removeUpdate(DocumentEvent e) {
verify();
}
#Override
public void changedUpdate(DocumentEvent e) {
verify();
}
});
txtVID.setText(null);

How to set list of symbles converted to alphabet?

I'm making a system to convert Morse cord to English alphabet. I'm using JTextfeild called "write" to type text and another JTextfeild call "View" to view which is typed on write.
But I can only set one Morse cord for one time.
As an example if I type A on "Write" textfeild it it is only printing ".-" . And when I type "B" again then view textfeild set "-..." . I want to print number of letters.
Given below is my source cord.
private void writeKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == 65) {
view.setText(".-");
} else if (evt.getKeyCode() == 66) {
view.setText("-...");
} else if (evt.getKeyCode() == 67) {
view.setText("-.-.");
} else if (evt.getKeyCode() == 68) {
view.setText("-..");
} else if (evt.getKeyCode() == 69) {
view.setText(".");
} else if (evt.getKeyCode() == 70) {
view.setText("..-.");
} else if (evt.getKeyCode() == 71) {
view.setText("--.");
} else if (evt.getKeyCode() == 72) {
view.setText("....");
} else if (evt.getKeyCode() == 73) {
view.setText("..");
} else if (evt.getKeyCode() == 74) {
view.setText(".---");
} else if (evt.getKeyCode() == 75) {
view.setText(".-.-");
} else if (evt.getKeyCode() == 76) {
view.setText(".-..");
} else if (evt.getKeyCode() == 77) {
view.setText("--");
} else if (evt.getKeyCode() == 78) {
view.setText("-.");
} else if (evt.getKeyCode() == 79) {
view.setText("---");
} else if (evt.getKeyCode() == 80) {
view.setText(".--.");
} else if (evt.getKeyCode() == 81) {
view.setText("--.-");
} else if (evt.getKeyCode() == 82) {
view.setText(".-.");
} else if (evt.getKeyCode() == 83) {
view.setText("...");
} else if (evt.getKeyCode() == 84) {
view.setText("-");
} else if (evt.getKeyCode() == 85) {
view.setText("..-");
} else if (evt.getKeyCode() == 86) {
view.setText("...-");
} else if (evt.getKeyCode() == 87) {
view.setText(".--");
} else if (evt.getKeyCode() == 88) {
view.setText("-..-");
} else if (evt.getKeyCode() == 89) {
view.setText("-.--");
} else {
view.setText("--..");
}
}
I'm making a system to convert Mose cord to English alphabet. I'm
using jtextfeild called "write" to type text and another jtextfeild
call "View" to view which is typed on write.
use DocumentListener for JTextComponents instead of low_level KeyListener, otheriwise you can't be able to input sequence of chars from (for example) Ctrl+C (SystemClipBoard), or remove selected chars, then output to anther JComponents freeze without any, no changes are made, because KeyListener can firing an Event from single Char only
plus you can use DocumentFilter in the case that you want to replace, remove, modify single char or chars sequence typed by user into JTextField
for example
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TextLabelMirror {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(20);
private JTextField field1 = new JTextField(20);
public TextLabelMirror() {
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
field1.setText(field.getText());
}
});
}
});
mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
mainPanel.add(field);
mainPanel.add(field1);
}
public JComponent getComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("TextLabelMirror");
frame.getContentPane().add(new TextLabelMirror().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
You should not use the event that way. Get the 'write' text as string and work on it:
private void writeKeyReleased(java.awt.event.KeyEvent evt) {
String input = write.getText();
StringBuilder output = new StringBuilder();
for(int cIndx = 0; cIndx < input.length(); ++cIndx){
output.append(convertChar(input.charAt(cIndx)));
}
}
private String convertChar(char c)
{
// TODO Your conversion method, modified a little:
if( c == 'a' || c == 'A') return ".-";
if( c == 'b' || c == 'B') return "-...";
// etc....
return ""; // handle as you like this case.
}

Get key combinations

How can I get key combination of keys on keyboard E.G. (Ctrl+somekey, Alt+somekey) with Java?
I use KeyEvent listener, MouseEvent listener for all keys on keyboard. I can catch all key event on keyboard by using that listener. But, I cannot catch key combination such as (Ctrl+Alt+Del)....etc.
public void keyPressed(KeyEvent kevt) {
if(kevt.getKeyChar()=='c') {
if(kevt.isAltDown())
//Code if Alt+c pressed
if(kevt.isControlDown())
//Code if Ctrl+c pressed
if(kevt.isShiftDown())
//Code if Shift+c pressed
if(kevt.isAltDown()&&kevt.isControlDown()&&(!kevt.isShiftDown()))
//Code if Alt+Ctrl+c pressed
if(kevt.isAltDown()&&kevt.isShiftDown()&&(!kevt.isControlDown()))
//Code if Alt+Shift+c pressed
if(!(kevt.isAltDown())&&kevt.isControlDown()&&(kevt.isShiftDown()))
//Code if Shift+Ctrl+c pressed
if(kevt.isAltDown()&&kevt.isControlDown()&&kevt.isShiftDown())
//Code if Alt+Ctrl+Shift+c pressed
}
Use the above code, use any character
If you want to check if Alt+C+E is pressed do the following
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.swing.*;
public class Sample implements KeyListener {
private JTextField lbl=new JLabel("Hello");
private JPanel pnl=new JPanel(new BorderLayout());
private JFrame frm=new JFrame ("Sample");
int []arr;int i=0;
public Sample() {
pnl.add("North", lbl);
frm.setContentPane(pnl);
frm.pack();
frm.setVisible(true);
lbl.addKeyListener(this);
arr= new int[3];
public void keyPressed(KeyEvent key) {
arr[i]=key.getKeyCode();
i++;
if((arr[0]==VK_ALT||arr[1]==VK_ALT||arr[2]==VK_ALT)&& (arr[0]==VK_C||arr[1]==VK_C||arr[2]==VK_C)&&(arr[0]==VK_E||arr[1]==VK_E||arr[2]==VK_E)) {
//Code you want
}
}
public void keyReleased(KeyEvent evt) {
arr[i]=null;
}
public void keyTyped(KeyEvent kvt) {
}
}
}
Many of these answers seem very complicated, just thought I'd add my solution.
I wrote a KeyBinder class:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Hashtable;
public abstract class KeyBinder implements KeyListener
{
private Hashtable<Integer, Boolean> keyMap;
private int[] keyCodes;
public KeyBinder(final int... keyCodes)
{
this.keyMap = new Hashtable<>();
this.keyCodes = keyCodes;
}
#Override
public void keyTyped(final KeyEvent e) { }
#Override
public void keyPressed(final KeyEvent e)
{
getKeyMap().put(e.getKeyCode(), true);
if (getKeysDown())
{
onKeysDown();
}
}
#Override
public void keyReleased(final KeyEvent e)
{
getKeyMap().put(e.getKeyCode(), false);
}
private Hashtable<Integer, Boolean> getKeyMap()
{
return this.keyMap;
}
public boolean getKeysDown()
{
for (final int key : this.keyCodes)
{
if (getKeyMap().containsKey(key))
{
if (!getKeyMap().get(key))
{
return false;
}
} else {
return false;
}
}
return true;
}
public abstract void onKeysDown();
}
And then on my control:
final KeyBinder binder = new KeyBinder(KeyEvent.VK_ALT, KeyEvent.VK_A)
{
#Override
public void onKeysDown()
{
System.out.println("Alt+A");
}
};
startButton.addKeyListener(binder);
Easy :)
#Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode()==KeyEvent.VK_CONTROL) { ctrl = true; }
else if (evt.getKeyCode()==KeyEvent.VK_SHIFT) { shift = true; }
else if (evt.getKeyCode()==KeyEvent.VK_ALT) { alt = true; }
else {
keyHit = KeyEvent.getKeyText( evt.getKeyCode() );
System.out.println("Key Hit is "+keyHit);
}
processLocalKeyEvent(evt);
}
#Override
public void keyReleased(KeyEvent evt) {
if (evt.isControlDown() && keyHit != "") ctrl = true;
if (evt.isAltDown() && keyHit != "") alt = true;
if (evt.isShiftDown() && keyHit != "") shift = true;
if (ctrl) sb.append("Ctrl");
if (shift) sb.append("Shift");
if (alt) sb.append("Alt");
if (!ctrl && !shift && !alt) {
sb.append(keyHit);
} else {
sb.append("_"+keyHit);
}
if (ctrl || shift || alt) {
Thread thread = new Thread();
try {
thread.sleep(300);
rfbProto.capture();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ((ctrl || shift || alt) && keyHit=="") {
rfbProto.capture();
} else if ((!ctrl || !shift || !alt) && keyHit!="") {
rfbProto.capture();
}
ctrl = false;
shift = false;
alt = false;
keyHit = "";
sb = new StringBuffer();
processLocalKeyEvent(evt);
}
private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {
System.out.println(evt.getKeyCode()); //showing code of released button
if(evt.isControlDown() && evt.getKeyCode()==40) // 40 is code for arrow down
{
//if ctrl is pressed and arrow down is released
System.out.println("Released " + evt.getKeyCode());
}
Simple version

Java detect CTRL+X key combination on a jtree

I need an example how to add a keyboard handler that detect when Ctrl+C , Ctrl+X , Ctrl+C pressed on a JTree.
I were do this before with menu shortcut keys but with no success.
You can add KeyListeners to any component (f)
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use KeyListener for example :
jTree1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_C) {
JOptionPane.showMessageDialog(this, "ctrl + c");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_X) {
JOptionPane.showMessageDialog(this, "ctrl + x");
} else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
JOptionPane.showMessageDialog(this, "ctrl + v");
}
}
});
Hope that helps.
Use Key Bindings.
initComponents();
KeyboardFocusManager ky=KeyboardFocusManager.getCurrentKeyboardFocusManager();
ky.addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID()==KeyEvent.KEY_RELEASED && (e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("Dhanushka Tharindu");
}
return true;
}
});
But menu shortcut accelerators are the way to do this normally: myMenuItem.setAccelerator(KeyStroke.getKeyStroke("control C"));

Categories