The default listner has only character value for character keys, and code for all of them is VK_UNDEFINED, but this make difference between characters and system keys processing.
How to handle all keys with one method, independently of its type?
This is a problem, because I try to save key in a text file, so I need to check if there is a code or a character to parse this file back.
It works for me:
import java.awt.event.*;
import javax.swing.*;
class TestKeyCode implements KeyListener {
public void keyPressed(KeyEvent e)
{
System.out.println("keyPressed(KeyEvent e)");
int code= e.getKeyCode();
System.out.println("code = " + code);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setSize(800, 800);
TestKeyCode tkc = new TestKeyCode();
jf.addKeyListener(tkc);
jf.setVisible(true);
}
}
Related
So, I'm fairly new to programming and I like to fiddle with it and one day my friend asked me to make a program where when you click, "ctrl" and "s" would be "pressed". I looked at lots of forums trying to make a functional code but, since I'm new to Java, I only got separate pieces of codes and threw it all together.
My code looks like this:
import java.awt.event.MouseEvent;
import java.awt.*;
import java.awt.event.*;
import java.awt.Robot;
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("press any key to exit.");
keyboard.next();
System.exit(0);
}
public void mouseClicked(MouseEvent evt) {
try {
Robot robot = new Robot();
// Simulate a key press
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException e) {
}
}
}
Your program has no GUI and, therefore, nothing to invoke your mouse listener. The code within the listener appears correct, all you need to do is search for how to create a basic GUI and add the mouse listener to it so you get the results you want.
The following code may help you to handle Ctrl + S
public class SwingApp1 extends JFrame implements KeyListener {
public SwingApp1() {
setSize(500, 500);
setLocationRelativeTo(null);
setBackground(Color.blue);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingApp1 main = new SwingApp1();
main.setVisible(true);
}
#Override
public void keyTyped(KeyEvent evt) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Pressed=>" + e.getKeyCode());
if (e.getKeyCode() == 83) {
System.out.println("Pressed Ctrl + S");
} // Ctrl + S
}
#Override
public void keyReleased(KeyEvent e) {
}}
I want to add keyListner on Input Dialog. When i press a key it will gives key code of pressed key. Below is complete code for JTextField its working for JTextField. I tried it on Input Dialog via String n = JOptionPane.showInputDialog("enter a key") but it says that keyListner unidentified for String operation.
*please edit my code for Input dialog
import java.awt.event.*;
import javax.swing.*;
public class KeyListnerExample extends JFrame implements KeyListener{
String KeyCodeT = JOptionPane.showInputDialog("enter a key");//A Text Field that will display the key code.
public KeyListnerExample(){
KeyCodeT.addKeyListener(this);//Listens for key inputs in the text field
KeyCodeT.setEditable(false);//disallow user input into the Text field.
add(KeyCodeT);//add the text field to the screen
setSize(300,300);//set the screen size
setVisible(true);//show the window on screen.
}
//Called when the key is pressed down.
public void keyPressed(KeyEvent e){
System.out.println("Key Pressed!!!");
e.getKeyCode();
System.out.println("key code is: " +e.getKeyCode());
}
//Called when the key is released
public void keyReleased(KeyEvent e){
System.out.println("Key Released!!!");
KeyCodeT.setText("Key Code:" + e.getKeyCode());//displays the key code in the text box
}
//Called when a key is typed
public void keyTyped(KeyEvent e){
}
public static void main(String[] args){
KeyListnerExample key = new KeyListnerExample();
}
}
You can try something like below :
Here you can create a text field by adding keyListener and that text field can be passed to the JoptionPane .
public static void main(String[] args) {
JFrame parent = new JFrame();
JOptionPane optionPane = new JOptionPane();
JTextField field = getField();
optionPane.setMessage(new Object[]{"Type something: ", field});
optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(parent, "My Customized OptionPane");
dialog.setVisible(true);
}
private static JTextField getField() {
JTextField field = new JTextField();
field.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Input: " + e.getKeyChar());
}
#Override
public void keyReleased(KeyEvent e) {
}
});
return field;
}
Here's a hint for what you can do:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class KeyListnerExample extends JFrame implements KeyListener{
JTextField KeyCodeT;
public KeyListnerExample(){
JPanel panel = new JPanel();
KeyCodeT = new JTextField();
KeyCodeT.setOpaque(false);
panel.setLayout(new GridLayout(1,1));
panel.add(KeyCodeT);
JOptionPane.showOptionDialog(null, panel, "Enter Key Code", JOptionPane.CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
KeyCodeT.addKeyListener(this);//Listens for key inputs in the text field
KeyCodeT.setEditable(false);//disallow user input into the Text field.
add(KeyCodeT);//add the text field to the screen
setSize(300,300);//set the screen size
setVisible(true);//show the window on screen.
}
//Called when the key is pressed down.
public void keyPressed(KeyEvent e){
System.out.println("Key Pressed!!!");
e.getKeyCode();
System.out.println("key code is: " +e.getKeyCode());
}
//Called when the key is released
public void keyReleased(KeyEvent e){
System.out.println("Key Released!!!");
KeyCodeT.setText("Key Code:" + e.getKeyCode());//displays the key code in the text box
}
//Called when a key is typed
public void keyTyped(KeyEvent e){
}
public static void main(String[] args){
KeyListnerExample key = new KeyListnerExample();
}
}
As you can see, I created a JPanel and added text field to it instead. Its easier to manage that way. Then finally used JOptionPane's OptionDialog to display stuff.
You can also use KeyCodeT.setBorder(null); if you dont want that black border. But that will give you an absurd dialog where you will have to make a guess-click in the middle.
EDIT: (Practically what #kamel2005 said in his answer).
Create a JPane Control that contains the control that will broadcast the key event to your key Listener.
for example JTextField and then add your key listener to text field.
the Pane can be passed as a parameter to "JOptionPane"
JPanel jPane = new JPanel();
TextField field = new TextField();
jPane.add(field);
field.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
if (JOptionPane.showConfirmDialog(null,jPane,"Panel Title", JOptionPane.OK_CANCEL_OPTION)== JOptionPane.OK_OPTION) {
System.out.println(field.getText());
}
I have been playing around with Java and I added a KeyListener. When I type a key it prints "0" and I would like it to print the key code.
Key.java
import java.awt.event.*;
public class Key implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + Integer.toString(e.getKeyCode()));
}
}
Main.java
public void init() {
addKeyListener(new Key());
addMouseListener(new Mouse());
this.setBackground(new Color(100, 100, 255));
this.setSize(screen);
}
Thanks for all the help!
Just read the doc :
void keyTyped(KeyEvent e)
Invoked when a key has been typed. See the class description for
KeyEvent for a definition of a key typed event.
So go through the description :
public int getKeyCode()
Returns the integer keyCode associated with the key in this event.
Returns: the integer code for an actual key on the keyboard. (For
KEY_TYPED events, the keyCode is VK_UNDEFINED.)
And the constant VK_UNDEFINED is :
public static final int VK_UNDEFINED = 0;
So that's totally normal you only get 0.
You should use :
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + e.getKeyChar());
}
Here's an example using the three methods.
For KEY_TYPED event, the Key Code is undefined. Check the java docs:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()
Use getKeyChar() instead.
Hello I'm currently working in my java file.
I'd like to add an event on JFormattedTextField when I press the enter key.
This is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.text.ParseException;
public class Test extends JFrame implements ActionListener
{
JFormattedTextField phoneField;
Test()
{
setTitle("JFormatted Text");
setLayout(null);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##########");
} catch (ParseException e) {
e.printStackTrace();
}
phoneField = new JFormattedTextField(mask);
phoneField.setBounds(20, 20, 150, 30);
phoneField.addActionListener(this);
setVisible(true);
setSize(200, 200);
getContentPane().add(phoneField);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== phoneField)
{
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
}
it works but their the user needs to enter 10 digits.
Add an ActionListener to the field. It is better than using the (low level) KeyListener and will conform to whatever that OS accepts as 'end of entry'.
Don't use KeyListener instead use DocumentListener.
It has the following methods which captures the changes in the JTextField
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent arg0) {
// Gives notification that a portion of the document has been removed.
}
#Override
public void insertUpdate(DocumentEvent arg0) {
// Gives notification that there was an insert into the document.
}
#Override
public void changedUpdate(DocumentEvent arg0) {
// Gives notification that an attribute or set of attributes changed.
}
});
You could add a keyListener instead.
phonefield.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_ENTER){
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
});
If this isn't your problem, you should expand a little and clarify.
EDIT:
As comments and other answers pointed out, you should go for an ActionListener instead. Reasoning can be found below.
What I want to do is the moment I pressed the keyboard, whatever is written on the textfield will be shown in the System.out.printLn(). but for every type I make, it will only be shown if I pressed another key.
for example.. I press 'A' ...then a blank space will be shown.
I press 'B' ...then 'A' will be shown.
I press 'C' ...then 'AB' will be shown.
what I want is if I press 'A' ...then 'A' will be shown...etc
is it possible? I also tried this on keyTyped() but the result is just the same..
here is my short code for this...
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class NewClass extends JFrame implements KeyListener{
JTextField tf = new JTextField();
NewClass(){
this.setLayout(null);
tf.setBounds(50, 50, 200, 30);
add(tf);
tf.addKeyListener(this);
}
public static void main(String[] args) {
NewClass r = new NewClass();
r.setVisible(true);
r.setSize(300, 200);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println(tf.getText());
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Any suggestions? thanks in advance :)
The problem is that keyPressed is being called before the TextBox is updated.
Instead of
tf.addKeyListener(this);
Try using this:
tf.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
printIt();
}
public void removeUpdate(DocumentEvent e) {
printIt();
}
public void insertUpdate(DocumentEvent e) {
printIt();
}
public void printIt() {
System.out.println(tf.getText());
}
You'll need to import javax.swing.event.DocumentEvent and javax.swing.event.DocumentListener.